我最近注意到我可以在 .pipe()
中返回一个值,但不能在 .subscribe()
中返回一个值。
这两种方法有什么区别?
例如,如果我有这个功能,我们称它为“存款”,如果我这样做,它应该返回账户余额:
deposit(account, amount){
return this.http.get('url')
.subscribe(res => {
return res;
}
}
它返回一个可观察对象,如果我这样做:
deposit(account, amount){
return this.http.get('url')
.pipe(
map(res => {
return res;
});
);
}
它按预期返回帐户余额。
为什么?
最佳答案
pipe
方法用于链接可观察操作符,subscribe
方法用于激活可观察对象并监听发出的值。
添加了 pipe
方法以允许 webpack 从最终的 JavaScript 包中删除未使用的运算符。它可以更轻松地构建较小的文件。
For example if I have this function, let's call it 'deposit', which supposed to return the account balance, if I do this:
deposit(account, amount){ return this.http.get('url') .subscribe(res => { return res; } }
It returns an observable
这不是它返回的内容。它返回调用 Subscribe
时创建的 Subscription
对象。
and if I do this:
deposit(account, amount){ return this.http.get('url') .pipe( map(res => { return res; }); ); }
It returns the account balance as expected.
这不是它返回的内容。它返回一个使用 map
运算符的 Observable
。您示例中的 map 运算符什么都不做。
关于javascript - RXJS 可观察对象上方法 .pipe() 和 .subscribe() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51269372/