RXJS observable 方法 .pipe() 和 .subscribe() 的区别 [英] Difference between the methods .pipe() and .subscribe() on a RXJS observable

查看:37
本文介绍了RXJS observable 方法 .pipe() 和 .subscribe() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近注意到我可以在 .pipe() 内返回一个值,但不能在 .subscribe() 内返回.

I recently notice that I can return a value inside .pipe() but not 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;
    }
}

它返回一个 observable,如果我这样做:

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.

那为什么?

推荐答案

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

The pipe method is for chaining observable operators, and the subscribe is for activating the observable and listening for emitted values.

添加了 pipe 方法以允许 webpack 从最终的 JavaScript 包中删除未使用的运算符.它可以更轻松地构建更小的文件.

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

例如,如果我有这个功能,我们称之为存款",如果我这样做,它应该返回账户余额:

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;
    }
}

它返回一个可观察的

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

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

如果我这样做:

deposit(account, amount){
    return this.http.get('url')
    .pipe(
        map(res => {
            return res;
        });
    );
}

它按预期返回帐户余额.

It returns the account balance as expected.

这不是它返回的内容.它返回一个使用 map 操作符的 Observable.您示例中的地图运算符什么也不做.

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

这篇关于RXJS observable 方法 .pipe() 和 .subscribe() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆