如何链接 rxjs observable

How to chain rxjs observable

我来自 Angular1,喜欢链接承诺,我希望有类似的行为。

我在 someclass 中有一个方法:-

{.........
      doLogin (username, password) {
            .......
            .......
            return this.http.get(api).subscribe(
                    data => {.....}, //enters here
                    err => {.....}
        }

然后我调用这个方法:-

 someclass.doLogin(username, password).subscribe(
           data => { }, //Not getting called
            err => { }
 }

正如我在上面代码的评论中提到的,订阅者没有在调用者中调用 class。

关于如何做到这一点有什么建议吗?

其实你return是subscribe方法的对象。这是一个订阅,而不是一个可观察的。因此,您将无法(再次)订阅 returned 对象。

Observables 允许基于可观察运算符构建数据流链。这取决于你想做什么。

如果您只是触发某些东西或从您的服务中设置服务 属性,您可以使用 do 运算符和 catch 运算符来处理错误:

doLogin (username, password) {
  .......
  .......
  return this.http.get(api).do(data => {
    .....
    // Call something imperatively
  })
  .catch(err => {
    .....
    // Eventually if you want to throw the original error
    // return Observable.throw(err);
  });
}

不要忘记包含这些运算符,因为它们不是 Rxjs 开箱即用的:

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

或全局(所有运营商):

import 'rxjs/Rx';

查看相关问题: