Adam
Adam

Reputation: 1011

Correct way to work with angular http calls and pass results to subscriber

I want to make requests with a service in my application. I want to pass the subscription on to the caller as is the usual behaviour, but I want to be able to also intercept the result, act on it but not change it, and carry on.

For example:

return this.http.get<LicenseKeyAndUsageModel>('api/license')
    .map(data => {
        this.hasValidLicenseKeyInternal.next(!data.isExpired);
        return data;
    })
    .catch((error: HttpErrorResponse) => {
        if (error.status === 404) {
            this.hasValidLicenseKeyInternal.next(false);
            return Observable.throw(new LicenseKeyMissingError());
        }
        else
            return Observable.throw(error);
    });

So in this case, I'm retriving the current license key, and updating a service level value as to whether the license key is valid, and still passing the result to the original subscriber.

Basically does this seem like the right approach? Or should I be doing something more 'Observable-y' like with multicast or something else?

Upvotes: 1

Views: 138

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 19632

Rxjs tap is what you are after .

Check this more info.

Sorry for not posting a big answer accessing thorough mobile.

Upvotes: 1

martin
martin

Reputation: 96949

This is what the do() operator (or tap() in RxJS 5.5) is intended to do.

It's true you could use map() for this as well but you need to remember to always return the original value. Also what you want seems to be a "side-effect" (you want to perform actions that affect application state outside of the observable chain) and this is what do() is made for.

Upvotes: 4

Related Questions