angular – 如何链接rxjs可观察

前端之家收集整理的这篇文章主要介绍了angular – 如何链接rxjs可观察前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我来自Angular1,就像链接承诺一样,我希望有类似的行为.

我在某类中有一个方法: –

  1. {.........
  2. doLogin (username,password) {
  3. .......
  4. .......
  5. return this.http.get(api).subscribe(
  6. data => {.....},//enters here
  7. err => {.....}
  8. }

然后我称之为这种方法: –

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

正如我在上面的代码中所提到的那样,在调用者类中没有调用subscribe.

有关如何做到这一点的任何建议?

实际上,您返回subscribe方法的对象.这是订阅而不是可观察的.因此,您将无法再次订阅返回的对象.

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

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

  1. doLogin (username,password) {
  2. .......
  3. .......
  4. return this.http.get(api).do(data => {
  5. .....
  6. // Call something imperatively
  7. })
  8. .catch(err => {
  9. .....
  10. // Eventually if you want to throw the original error
  11. // return Observable.throw(err);
  12. });
  13. }

不要忘记包含这些运算符,因为Rxjs不包含这些运算符:

  1. import 'rxjs/add/operator/do';
  2. import 'rxjs/add/operator/catch';

或全球(所有操作符):

  1. import 'rxjs/Rx';

查看相关问题:

> Angular 2,best practice to load data from a server one time and share results to components
> Angular 2 HTTP GET with TypeScript error http.get(…).map is not a function in [null]

猜你在找的Angularjs相关文章