Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
313 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...