我来自Angular1,就像链接承诺一样,我希望有类似的行为.
我在某类中有一个方法: -
{.........
doLogin (username, password) {
.......
.......
return this.http.get(api).subscribe(
data => {.....}, //enters here
err => {.....}
}
Run Code Online (Sandbox Code Playgroud)
然后我称这种方法: -
someclass.doLogin(username, password).subscribe(
data => { }, //Not getting called
err => { }
}
Run Code Online (Sandbox Code Playgroud)
正如我上面提到的对上述代码的评论,订阅不会在调用者类中被调用.
有关如何做到这一点的任何建议?
事实上,您返回了该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);
});
}
Run Code Online (Sandbox Code Playgroud)
不要忘记包含这些运算符,因为 Rxjs 并未包含这些运算符:
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
Run Code Online (Sandbox Code Playgroud)
或全局(所有运营商):
import 'rxjs/Rx';
Run Code Online (Sandbox Code Playgroud)
查看相关问题:
| 归档时间: |
|
| 查看次数: |
7079 次 |
| 最近记录: |