Search code examples
angularangular2-services

Return http status code in component from Service - Angular 2


I'm having a problem in returning an object in my Http Service in catch to my component:

Here is my code in my service:

login(username,password){
        let headers = new Headers();
        headers.append('Content-Type','application/json');

        return this.http.post(this.configEnvironment.url() + "oauth/access_token",
            JSON.stringify(
                {
                    username: username,
                    password: password,
                    grant_type: "password",
                    client_id: "xxxx",
                    client_secret: "xxxxx"
                }
            ),
            { headers }
        )
        .map(res => res.json())
        .catch((err:Response) => {
            let details = err.json();

            return Observable.throw(details);
         });

     }

Here's my code in my component:

this.loginService.login(this.model.username,this.model.password)
            .subscribe(
                data => console.log(data),
                error => {
                    // var details = error.json();
                    console.log(error);
                },
                ()  =>  console.log("Finished")
            );

It works fine when I just return the json error like this:

let details = err.json();
    return Observable.throw(details);

But when I try to add the http response status code like this:

return  { status: err.status, error: Observable.throw(details) }

It gives me an error of:

"Argument of type '(err: Response) => { status: number; error: ErrorObservable; }' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput'. Type '{ status: number; error: ErrorObservable; }' is not assignable to type 'ObservableInput'. Type '{ status: number; error: ErrorObservable; }' is not assignable to type 'ArrayLike<{}>'. Property 'length' is missing in type '{ status: number; error: ErrorObservable; }'."

My goal is just to include the http response code in the return of catch.


Solution

  • try below code,

    .catch((err:Response) => {
                let details = {detail:err.json(),status: err.status};
                return Observable.throw(details);
     });