0

I have a custom http service which overrides default angular 2 http service. This service sets custom default options and set loader on request start and hides loader on request completion.

I also want to add, the functionality to redirect user to the login page in case if Unauthorized error (401, 403) is received from server. For example below is my http method

get(url: string, options?: RequestOptionsArgs): Observable<any> {
        this.setLoadingStatus();
        options = this.prepareOptions(options);
        let that = this;
        return super.get(url, options)
            .map(res => {
                this.clearLoadingStatus();
                return res.json();
            })
            .catch(function (err) {
                //redirects user to login and display alert
                that._gs.alertUnauthorized();
                return Observable.empty();
            });
    }

But when test it in browser i.e. make a request for protected page that returns 401 in case of unauthorized request, it doest redirect to the login page but console displays below error:

GET http://localhost:49547/api/protected/ 401 (Unauthorized)
EXCEPTION: Observable_1.Observable.empty is not a function
ORIGINAL STACKTRACE:
TypeError: Observable_1.Observable.empty is not a function

Can anyone please guide?

1
  • Try super.get().map((res) => {}, (err) => {}); syntax? Commented Oct 1, 2016 at 10:29

1 Answer 1

2

You need to import the empty function:

import 'rxjs/add/observable/empty'
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this was helpful. Please also guide that if using Observable.empty() in this case is appropriate, or is there any other better option?
I still see the below error line printed in console "zone.js:1274 GET localhost:49547/proteccted 401 (Unauthorized)", is it okay? or is it an exception that needs to be handled?
I think it's just a debugging thing. Returning Observable.empty() supresses the error, so if that's what you want, you're golden.
When server returns 401 unauthorized, I want to redirect to Login page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.