Javascript RXJS observable 方法 .pipe() 和 .subscribe() 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51269372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:48:22  来源:igfitidea点击:

Difference between the methods .pipe() and .subscribe() on a RXJS observable

javascriptangularrxjs

提问by Amadou Beye

I recently notice that I can return a value inside .pipe()but not inside .subscribe().

我最近注意到我可以返回一个 inside.pipe()而不是 inside的值.subscribe()

What is the difference between these two methods?

这两种方法有什么区别?

For example if I have this function, let's call it 'deposit', which is 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 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.

它按预期返回帐户余额。

So why?

所以为什么?

采纳答案by Reactgular

The pipemethod is for chaining observable operators, and the subscribeis for activating the observable and listening for emitted values.

pipe方法用于链接 observable 操作符,subscribe用于激活 observable 并监听发出的值。

The pipemethod was added to allow webpackto drop unused operators from the final JavaScript bundle. It makes it easier to build smaller files.

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:

例如,如果我有这个函数,我们称之为“存款”,它应该返回账户余额,如果我这样做:

That isn't what it returns. It returns the Subscriptionobject created when you called Subscribe.

那不是它返回的内容。它返回Subscription调用时创建的对象Subscribe

it returns the account balance as expected.

它按预期返回帐户余额。

That isn't what it returns. It returns an Observablewhich uses a mapoperator. The map operator in your example does nothing.

那不是它返回的内容。它返回一个Observable使用map运算符的。您示例中的 map 运算符不执行任何操作。