Angular / rxjs承诺 - 等待一个电话完成

时间:2017-12-12 16:22:52

标签: angular rxjs

我在制作http电话时苦苦挣扎,等待前一个电话完成,然后才能完成下一个。 getThings调用我的HTTP服务,最终发送一条getMessage订阅的消息。我这样做的原因是因为多个组件使用此服务和getThings()。我想我需要使用promises但不知道如何实现。

我的组件

getThings(endpoint:any){
 this.getThingsService.getThings(endpoint);
 this.getThingsService.clearMessage();
 this.subscription = this.getThingsService.getMessage()
  .takeUntil(this.ngUnsubscribe)
  .subscribe(message => {
    if(message) {
      this.data = message;        
    }
  })
}

//I want to wait for getThings to finish before calling getOtherThings.

getOtherThings(data:any){
 //make another http call
}

服务提供商

getThings(link:any){
interface ItemsResponse {
  results: string[];
}
this.http
  .get<ItemsResponse>(link, {
    observe: 'response'     
  })
  .retry(3)
  .takeUntil(this.ngUnsubscribe)
  .subscribe(
    (event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Sent:
          break;
        case HttpEventType.Response:
          this.handleData(event.body);
      }
    },
    (err: HttpErrorResponse) => {        
       //error        
    }
  )
  }

 handleData(allAppDetails: any){
  this.clearMessage();   
  this.sendMessage(allAppDetails);
 }

 sendMessage(message: {}) {
  this.subject.next(message);
 }

 clearMessage() {
  this.subject.next(null);
 }

 getMessage(): Observable<any> {
  return this.subject.asObservable();
 }

////////新解////////

成分:

getThings(endpoint){
 this.subscription = this.getThingsService.getThings(endpoint)
  .flatMap(res => {
    if(res){
      console.log("get things complete, call getOtherThings")        
    }
    return this.getThingsService.getOtherThings(endpoint)
  })

  //this doesnt seem to catch anything
  .catch(err => {
    throw err
  })
  .subscribe(
    res => { // res is the result of the second http request
      if(res){
        console.log("other things response");
      }
  },
    //would this catch errors for both http calls?
    err => {
      console.log(err)
    });

 }

服务

getThings(link:any) {
 interface ItemsResponse {
  results: string[];
 }
 return this.http
  .get<ItemsResponse>(link, {
    observe: 'response'       
  })

getOtherThings(link:any) {
 interface ItemsResponse {
  results: string[];
 }
 return this.http
  .get<ItemsResponse>(link, {
    observe: 'response'       
  })

如何使用此方法捕获http错误?

1 个答案:

答案 0 :(得分:1)

你不需要承诺这样做。您可以使用rxjs flatMap运算符完成此操作。

// component.ts
getThings(){
    this.getThingsService.getMessage()
        .flatMap(res => { // res is the result of the first http request
            // return observable of second http request;
            return this.getThingsService.getOtherMessage(); 
        })
        .subscribe(res => { // res is the result of the second http request
        });
}

所以发生的事情是getMessage()可观察的第一个被调用。完成后,将调用getOtherMessage() observable。