如何在http.request angular2中使用.catch()

时间:2017-11-03 08:30:21

标签: angular

我正在尝试在Angular中使用http.request - 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}));

在组件中:

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

如果服务器响应正常。没有问题。但如果我发送 res.status(401).send({error:err.message}),我在.catch()中没有得到任何回复。

请帮忙

2 个答案:

答案 0 :(得分:1)

访问错误就像这样:

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

对于状态,您可以在error.status

中将其设为.catch()

答案 1 :(得分:0)

在Angular 4的HttpClient实现中,您可以定义一个带有错误回调函数的订阅方法,如

.subscribe((resp)=> {// resp processing},(错误)=> {//错误方}}

具体请尝试以下代码,

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