2016-11-28 94 views
2

我有一个angular2 http响应的问题。angular2等待错误http响应

我想捕捉我的组件中的错误。

我的应用程序如何工作。 在我的组件,我在个人服务调用的函数:

var response = this.apiUser.login(username, password); 
alert(response); 

在我的服务,我尝试AUTH:

this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders }) 
      .subscribe(
       response => { 
        localStorage.setItem('id_token', response.json().token); 
        this.router.navigate(['home']); 
       }, 
       error => { 
        return error.json(); 
       }, 
       () => { } 
      ); 

当AUTH是确定的,一切工作正常。但是,当Auth失败时,我无法在我的组件中捕获响应。 (它的undefinied,因为警报在http调用之前执行...)

你能帮我吗!!! (当所有的代码只在我的组件中时,它正在工作,但我想滑我的代码...)

Ty。

+0

下面的代码:“我尝试执行代码auth“在'apiUser.login(){...}'中? –

回答

1

使用map()代替subscribe()

return this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders }) 
.map(
    response => { 
     localStorage.setItem('id_token', response.json().token); 
     this.router.navigate(['home']); 
    }, 
); 

返回观察到的,然后使用订阅您要在响应或错误到达

var response = this.apiUser.login(username, password) 
    .subscribe(
     response => alert(response), 
     error => alert(error), 
    ); 
+1

你是男人!我试图从3小时开始做这个...然后你来...泰特马特! – user3402182