Angular 5 链服务 observables 然后将 observable 返回给组件

vel*_*iam 0 observable rxjs angularjs

我需要打两次休息电话。休息呼叫 2 取决于休息呼叫 1。我想在继续之前将每个结果存储在服务中。然后我想向调用其余调用 1 的组件返回一个可观察值,以便该组件可以在出现问题时进行订阅。

来自服务的代码:

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);
      });
  });
Run Code Online (Sandbox Code Playgroud)

}

我可以正确链接它,但是调用它并订阅该调用的组件将显示未定义的响应。对此的任何帮助将不胜感激,因为我找不到关于这个确切用例的回复。

Lui*_*yfe 5

现场工作示例。使用map运算符(以及可出租运算符罪名),而不是链接一个新的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;
                  }));
          }));
  }
Run Code Online (Sandbox Code Playgroud)