javascript - RXJS 可观察对象上方法 .pipe() 和 .subscribe() 的区别

标签 javascript angular rxjs

我最近注意到我可以在 .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/

相关文章:

javascript - 如何将 html 元素添加到 tampermonkey

javascript - koa-router 无法与发电机一起使用

angular - 使用catchError运算符捕捉Angular 9中的错误

twitter-bootstrap - 试图关闭一个模态并打开另一个但都继续关闭

promise - 为什么 switchMap 运算符在与 Promise 一起使用时仅发出最后一个值?

Angular http请求可观察到的错误没有捕获错误?

javascript - "map is not a function"与 redux-orm 0.9.0

javascript - ammap气球点击事件

Angular 2 : getting RouteParams from parent component

rxjs - 去抖动和缓冲 rxjs 订阅