Angular 5链服务可观察对象然后将可观察对象返回给组件 [英] Angular 5 chain service observables then return observable to component

查看:67
本文介绍了Angular 5链服务可观察对象然后将可观察对象返回给组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

服务代码:

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.

推荐答案

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;
                  }));
          }));
  }

这篇关于Angular 5链服务可观察对象然后将可观察对象返回给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆