Angular 2 http发布返回200,但未返回任何响应 [英] Angular 2 http post is returning 200 but no response is returned

查看:81
本文介绍了Angular 2 http发布返回200,但未返回任何响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的http呼叫返回200,但未捕获任何响应.我的订阅中的代码未被点击.当我在邮递员中测试时,API返回数据.这是我的代码.

My http call is returning 200 but no response is captured. My code inside subscribe is not being hit. The API is returning data when I test in postman. Here is my code.

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函数解决了该问题.这是我的实现:

I was also facing the same problem. The problem was solved using the map function on Observables. Here is my implementation:

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函数返回响应.现在,可以通过以下方式在订阅函数中捕获此返回的响应:

Here the handleError is a function to catch the excceptions generated. This is a function in login.service.ts that sends the username and password to the api to get data. You can see that I am returning response from the map function in this service. Now, this returned response can be caught in subscribe function in following way:

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'])}
        );

这篇关于Angular 2 http发布返回200,但未返回任何响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆