2016-09-24 287 views
1

我的http呼叫正在返回200,但沒有響應被捕獲。 我的代碼裏面訂閱沒有被打到。當我在郵差測試中API正在返回數據。這是我的代碼。Angular 2 http post正在返回200,但沒有響應返回

getToken(authcode: string) { 

     var data = 'client_id=InspectWebApp_client&code=' + authcode + '&redirect_uri=http://localhost:3000&grant_type=authorization_code'; 
     let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
     let options = new RequestOptions({ headers: headers }); 
     this.http.post('https://fedloginqa.test.com/as/token.oauth2', data, options) 
      .subscribe((res: Response) => { 

       var resultsToken = res.json(); 
       localStorage.setItem("access_token",resultsToken.access_token) 
       //return this.inspections; 
      }) 

    } 

回答

2

我也面臨同樣的問題。使用Observables上的map函數解決了該問題。這裏是我的實現:

login(Username:string, Password:string) : Observable<Response>{ 
    let headers = new Headers(); 
    headers.append("Authorization", "Basic " + btoa(Username + ":" + Password)); 
    headers.append("Content-Type", "application/x-www-form-urlencoded"); 
    return this._http.post(this._baseUrl+"auth/login", " " , {headers: headers} ) 
     .map((response: Response) => { 
      return response;  
     }).catch(this.handleError); 
} 

這裏handleError是一個函數,以捕獲生成的概念。這是login.service.ts中的一個函數,它將用戶名和密碼發送到api以獲取數據。您可以看到,我正在返回此服務中地圖功能的響應。現在,該返回響應可以通過以下方式在訂閱功能中捕獲:

this._loginService.login(this.username, this.password) 
     .subscribe(
      (response) => { 
       //Here you can map the response to a type. 
       this.apiResult = <IUser>response.json(); 
      }, 
      (err) => { 
       //Here you can catch the error 
      }, 
      () => {this.router.navigate(['home'])} 
     ); 
相關問題