0

I am trying to use http.request in Angular - service::

let _request = new Request({
    method: "POST",
    body:body,
    // change url to "./data/data.junk" to generate an error
    url: "http://localhost:5000/user/contact",
    headers:new Headers({
      'Content-Type': 'application/json',
      'Authorization': 'Bearer '+token
    })
});

return this._http.request(_request)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw({status:error.status,message:error.json().error}));

And in component :

this._httpService.getContacts()
  .subscribe(
    (response) => {          
      console.log(response)
    }
  )

If response is OK from server. There is no issue. But if I am sending res.status(401).send({error:err.message}) , I not getting any response in .catch().

Please help

4
  • try: this._httpService.getContacts().subscribe( (response) => {console.log(response);} , (error) => {console.log(error);} ) Commented Nov 3, 2017 at 8:38
  • Now I am getting the err.message. But how can I get res.status? Commented Nov 3, 2017 at 8:43
  • you should be getting it in error.status in .catch() Commented Nov 3, 2017 at 8:46
  • great, i've also posted it as answer :) Commented Nov 3, 2017 at 8:50

2 Answers 2

1

to access error do it like :

this._httpService.getContacts().subscribe( 
(response) => {console.log(response);} , 
(error) => {console.log(error);} 
)

and for status, you can get it as error.status in .catch()

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

Comments

0

In HttpClient implementation of Angular 4, you can defined a subscribe method with error callback function like

.subscribe((resp)=>{//resp processing}, (err)=>{//error side})

to be specific try this code below,

this._httpService.getContacts()
  .subscribe(
    (response) => {          
      console.log(response)
    },
(err)=>{console.log(err, "Your Error Received from the server")}
  )

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.