Angular HTTP错误为空,未键入响应 [英] Angular HTTP Error Empty Untyped Response

查看:74
本文介绍了Angular HTTP错误为空,未键入响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个进行HTTP调用的Angular/JHipster应用程序.我想在我的Observable订阅中进行错误处理.

I have an Angular/JHipster application that makes HTTP calls. I want to do error handling in my Observable subscriptions.

但是,第一次调用错误处理程序时,err对象不是响应,而是原始的{} Object.所有后续的错误处理程序调用均具有有效的Response.

However, when the first time the error handler is invoked, the err object is not a response, it's a raw {} Object. All subsequent error handler invocations have a valid Response.

为什么会这样,怎么解决?

Why is this happening, and how do I fix it?

handleClickPost() {
    this.myService.doPost(this.body)
    .subscribe(
        (res: Response) => {
            this.responseOk = true;
        },
        (err: Response) => {
            // This is a HACK!
            // For some reason, the first time this error handler is invoked (after page load),
            // the response body is empty here and serializes to "{}".
            if (JSON.stringify(err) === '{}') {
                // first request always reaches here... WHY?
                this.handleClickPost(); // NB: workaround
                // err.json(); // results in null "method not found" error
            } else {
                // second request always reaches here... WHY?
                // (I want all requests to go here with a valid 'Response' object)
                this.showRequestFailed = true;
                this.errorResponse = err.json();
            }
        }
    );
}

MyService.ts:

doPost(body): Observable<Response> {
    return this.http.post(this.resourceUrl, body);
}

我的伪劣变通办法是在第一次出现空体故障后再次调用该方法,以获取键入的Response.

My shoddy workaround is to just call the method again after the first empty-body failure in order to get a typed Response.

注意:Angular 2和Angular 4都会发生这种情况.

NB: This behavior happens with both Angular 2 and Angular 4.

推荐答案

首先,您必须检查几件事以确保设置正确.

First you have to check few things to make sure your setup is correct.

  1. 在服务器端检查您是否为第一次请求发送了正确的JSON编码响应,即响应是否已正确序列化.

  1. Check in server side whether you are sending the proper JSON encoded response for the first time request i.e the response is correctly serialized or not.

检查POST请求this.body的有效负载是否已转换为json字符串,或者是否要将json数据发布到server.你应该用 如果要发送json数据,请在发送请求之前JSON.stringify(this.body).

check if the payload for the POST request this.body is already converted to json string or not if you are posting json data to server . You should use JSON.stringify(this.body) before sending the request if you are sending json data.

您应该在post()方法中使用map()/catch()来实际映射响应并捕获实际错误.

you should use map()/catch() in you post() method to actually map the response and catch the actual error.

因此您的代码应如下所示

So your code should look like below

MyService.ts:

doPost(body:any): Observable<Response> {
   let payload = JSON.stringify(body); // Stringify payload if you are using JSON data
   let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON for json request
   let options      = new RequestOptions({ headers: headers }); // Create a request option
   return this.http.post(this.resourceUrl, payload,options)
                        .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                        .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any;
}

MyComponent.ts:

handleClickPost() {
    this.myService.doPost(this.body)
    .subscribe(
        (res: any) => {
            this.responseOk = true;
        },
        (err: any) => {
            // Log errors if any
            console.log(err);
           }
        }
    );
}

或者您可以为catch()方法创建一个单独的错误处理程序,如下所示

or you can create a separate error handler for the catch() method like below

private handleError(error: any) {
      let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
       console.log(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

并在服务类中以这种方式.catch(this.handleError)使用它.

and use it this way .catch(this.handleError) in your service class.

这篇关于Angular HTTP错误为空,未键入响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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