Nicolas S.
Nicolas S.

Reputation: 173

Returning a value from a subscription

Having this code, I would like to return a string value from this subscription :

this.langPipe.transform(text).subscribe((res: any) => {
        return res['value']
    });

The transform langPipe function return a Observable<string>.

The fact is, this is of course not running and I don't understand who to do it with a map. On my template, I just want to show it in a title attribute of a div.

This is probably a duplicate and I saw similar threads but i really don't understand how it works.

If anyone has an idea, it will be so much help. Thank in advance !

Upvotes: 1

Views: 357

Answers (1)

Pac0
Pac0

Reputation: 23129

Subscription are here to trigger an action, and give a callback when value are emitted or when observable finishes / raises an error. For instance, one could set a variable in the component class depending on the emitted values. But subscription is not supposed to return a value.

If you need this value to be returned, so you need a transformation of the emitted values, then you can use map operator instead of subscribe.

The result will be an Observable<string>, though, so if you are using this result elsewhere, you can pipe this with async pipe.

So instead of {{ input | yourPipeReturningString }}, you can use {{ input yourPipeReturningObservble | async }}

Basically, the async Angular pipe will just subscribe to the underlying observable and return the value emitted.

Upvotes: 2

Related Questions