我来自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]