2017-05-17 6 views
1

私は、オブザーバブル内のオブザーバブルの結果に対してアクションを実行する必要があります。オブザーバブルが完了した後に実行されるアクションの完了後、どのように操作を実行しますか?

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がリロードされました。

コードを実行する前に2秒間待つだけで、オブザーバブルが2秒以内にうまくいく場合は正常に動作します。最も正しい方法は正しいアプローチではありません。

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

関連する問題