Angular 5 chain service observables then return observable to component

我的梦境 提交于 2019-12-24 19:30:09

问题


I have two rest calls I need to make. Rest call 2 depends on rest call 1. And I want to store each result in the service before proceeding. Then I want to return an observable to the component that calls rest call 1 so the component can subscribe in case of issues.

code from service:

login(username: string, password: string): Observable<AuthAccess> {
// rest call 1
return this.getAuthClient()
  .flatMap(res => {
    this.client = res.body;
    // rest call 2
    return this.authenticate(username, password)
      .flatMap(access => {
        this.userAccess = access.body;
        return Observable.of(this.userAccess);
      });
  });

}

I can get this to chain correctly, but the component that is calling this and subscribing to the call will show an undefined response. Any help on this would be greatly appreciated as I cannot find responses on this exact use case.


回答1:


Live working example. Use a map operator (and the lettable operatos sintax), instead of chain a new flatMap.

login(username: string, password: string): Observable<any> {
      // rest call 1
      return this.getAuthClient()
          .pipe(flatMap(res => {
              this.client = res.body;
              // rest call 2
              return this.authenticate(username, password)
                  .pipe(map(access => {
                      this.userAccess = access.body;
                      return this.userAccess;
                  }));
          }));
  }



回答2:


Try converting the first observable to a promise

login(username: string, password: string): Observable<AuthAccess> {
// rest call 1
return this.getAuthClient()
  .flatMap(res => {
    this.client = res.body;
 }).toPromise()
.then(function(){
    // rest call 2
    return this.authenticate(username, password)
      .flatMap(access => {
        this.userAccess = access.body;
        return Observable.of(this.userAccess);
      });
  });
}


来源:https://stackoverflow.com/questions/49659837/angular-5-chain-service-observables-then-return-observable-to-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!