Angular 2 http post返回200但没有返回任何响应

时间:2016-09-24 14:46:29

标签: rest angular angular2-http

我的http调用返回200,但未捕获任何响应。 我的订阅内部订阅未被点击。当我在邮递员中测试时,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;
            })

    }

1 个答案:

答案 0 :(得分:3)

我也遇到了同样的问题。使用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'])}
        );