【问题标题】:Angular 2 http post is returning 200 but no response is returnedAngular 2 http 帖子返回 200 但没有返回响应
【发布时间】:2016-09-25 01:20:15
【问题描述】:

我的 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;
            })

    }

【问题讨论】:

    标签: rest angular angular2-http


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多