我的 http 调用返回 200,但未捕获任何响应。 我的订阅内的代码没有被点击。当我在 postman 中测试时,API 正在返回数据。这是我的代码。
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;
})
}
最佳答案
我也遇到了同样的问题。使用 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以获取数据。您可以看到我正在从该服务中的 map 功能返回响应。现在,可以通过以下方式在订阅函数中捕获返回的响应:
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'])}
);
关于rest - Angular 2 http post 返回 200 但没有返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677629/