4

I have a loadSize() func in my angular2 project and it calls a getTotalNumberCampaigns() in my service and return a observable. and I subscribe to this observable to get the result.

this is my loadSize()

   loadSize() {
    this.campaignsService.getTotalNumberCampaigns().subscribe(value => {//async call
        this.campaignSize = value;
    }, (err)=> {}

    );
}

let's say there is an error with my getTotalNumberCampaigns() and it will fire the err=>{} in subscribe. My question is how do i know what the httpreponse status code is so that i can direct the user to take different action (if it is connection failed(502), the user should refresh. if it is access_token expiry(500), the page should be jump to login page)

this is my getTotalNumberCampaigns in service class

 getTotalNumberCampaigns(): Observable<number> {
    return this.http.get(`${this.apiUrl}/Count`, { headers: this.headers })
        .map<number>(res => <number>res.json())
}

why i get 200

9
  • 1
    it should be on err.status, check angular response Commented Mar 1, 2016 at 5:51
  • My getTotalNumberCampaigns() function returns a observable of NUMBER type. don't know if error happened,does it still return an observable of number? should I change it to Observable<any>? Commented Mar 1, 2016 at 6:00
  • No you don't need to change the observable type. The observable type will not change. Commented Mar 1, 2016 at 6:38
  • 1
    you could change the error callback to : (err:any) => console.log(err.status) Commented Mar 1, 2016 at 7:09
  • 1
    This: stackoverflow.com/a/33942337/3582411 helped me might consider takinga look at it Commented Apr 5, 2016 at 12:07

2 Answers 2

6

The returned error corresponds to the response itself, so you can use its status attribute to get the status code:

loadSize() {
    this.campaignsService.getTotalNumberCampaigns().subscribe(value => {//async call
        this.campaignSize = value;
    }, (err: any) => { console.log(err.status); console.log(err);}

    );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Strange. Do you use the catch operator previously in your data flow? The response object is provided when an error occurs. But you're free to catch it with this operator and use Objectable.throw to throw another one then. Is it your case?
I will start a new question since for this topic the question has already solved
0

In your loadSize method

loadSize() {
    this.campaignsService.getTotalNumberCampaigns().subscribe(value => {//async call
        this.campaignSize = value;
    }, (err)=> {}

    );
}

you should get the respone code by

value.status

Comments

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.