微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular – 如何链接rxjs可观察

我来自Angular1,就像链接承诺一样,我希望有类似的行为.

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

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

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

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

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

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

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

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';

查看相关问题:

> 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]

原文地址:https://www.jb51.cc/angularjs/141104.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐