Angular HTTP Error Empty Untyped Response

JJ *_*kar 13 error-handling promise typescript jhipster angular

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

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

为什么会发生这种情况,我该如何解决?

MyComponent.ts:

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();
            }
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

MyService.ts:

doPost(body): Observable<Response> {
    return this.http.post(this.resourceUrl, body);
}
Run Code Online (Sandbox Code Playgroud)

我的粗暴的解决方法是在第一次空体失败后再次调用该方法以获得打字Response.

注意:Angular 2和Angular 4都会出现这种情况.

小智 1

似乎是预检 Http OPTIONS 请求的问题。您是否验证了响应类型。

如果是这个问题,您可以通过修改内容标头来避免预检请求,如下所示。

   $http.defaults.headers.post["Content-Type"] = "text/plain"
Run Code Online (Sandbox Code Playgroud)

在此处阅读更多信息:为什么我收到 OPTIONS 请求而不是 GET 请求?