我需要對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);
我做了它的工作另一種方式。我會試試這個,並讓你知道它是否有效。非常感謝。 – anonym