在 RXJS 上观察到的. tube()方法和. scrib()方法之间的差异

我最近注意到,我可以在 .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;
});
);
}

它按预期返回帐户余额。

为什么?

113134 次浏览

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

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

It returns an observable

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

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.

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