2017-05-17 205 views
1

我需要對observable中的observable的結果執行一個操作。完成observable完成後要執行的操作後,如何執行操作?

Component

checkIn(room: Room) 
{ 
    this.roomService.checkIn(room.number).subscribe(
     response => { 
      this.checkInResponse = response; 
      // other codes 

      this.getRooms(); 

      // Perform the following line of code after getRooms() is complete, i.e. this.rooms has been reloaded. Right now, it executes instantaneously, i.e. before this.getRooms() is complete. 
      this.setRoom = this.roomFromNumber(room.number); 
     }, 
     error => { 
      console.log(error); 
     } 
    ); 
} 

getRooms() { 
    this.roomService.getRooms().subscribe(
     response => { 
     this.rooms = response; 
     }, 
     error => { 
     console.log(error); 
     } 
    ); 
} 

Service

getRooms(): Observable <any> { 
    return this.http.get('http://localhost:8000/api/rooms?token=' + this.token).map(
     (response: Response) => { 
      return response.json().rooms; 
     }); 
} 

checkIn(roomNumber: number) { 
    return this.http.post('http://localhost:8000/api/room/checkIn?token=' + this.token, 
    { 
     number: roomNumber 
    }, 
    { 
     headers: new Headers({ 
       'Content-Type' : 'application/json', 
       'X-Requested-With' : 'XMLHttpRequest', 
     }) 
    }); 
} 

在上面的代碼中的問題是,this.setRoom = this.roomFromNumber(room.number);this.getRooms()之前執行。 getRooms()完成後,我需要執行以下代碼行,即this.rooms已重新加載。

我可以簡單地執行以下操作,在執行代碼之前等待兩秒鐘,如果可觀察事件發生在兩秒鐘內,則工作正常;這絕對不是正確的做法。

setTimeout(() => this.setRoom = this.roomFromNumber(room.number), 2000); 

回答

1

你可以這樣做。

checkIn(room: Room) 
{ 
    this.roomService.checkIn(room.number).subscribe(
     response => { 
      this.checkInResponse = response; 
      // other codes 

      this.getRooms(() => { this.setRoom = this.roomFromNumber(room.number); });. 

     }, 
     error => { 
      console.log(error); 
     } 
    ); 
} 

getRooms(completeAction: any) { 
    this.roomService.getRooms().subscribe(
     response => { 
     this.rooms = response; 
     }, 
     error => { 
     console.log(error); 
     }, 
    () => { completeAction(); } 
    ); 
} 
+0

我做了它的工作另一種方式。我會試試這個,並讓你知道它是否有效。非常感謝。 – anonym

1
checkIn(room: Room) 
{ 
    this.roomService.checkIn(room.number).subscribe(
     (response) => { 
      this.checkInResponse = response; 
      // other codes 

      this.getRooms().subscribe(
      (data) => { 
       // executes after getRooms() has completed execution 
       this.setRoom = this.roomFromNumber(room.number); 
      }, 
      (error) => { 
       console.log(error); 
      }); 
     }, 
     (error) => { 
      console.log(error); 
     } 
    ); 
} 

getRooms() { 
    return this.roomService.getRooms().map(
      (response) => { 
       return response 
      } 
      ).catch((error) => { 
       return Observable.throw(error) 
      }); 
} 
+0

我明白這將如何工作。謝謝。 – anonym

相關問題