简体   繁体   English

Angular 8 响应缺少 _body 和标题

[英]Angular 8 Response Missing _body and Headers

Back-end code is C# in .NET targeting the 4.6.1 framework.后端代码是面向 4.6.1 框架的 .NET 中的 C#。 Front-end was recently upgraded from Angular 4 to Angular 8. Along with that webpack went from version 2.3 to version 4.41 and typescript from 2.2 to 3.2.4.前端最近从 Angular 4 升级到了 Angular 8。与此同时,webpack 从 2.3 版升级到了 4.41 版,typescript 从 2.2 升级到了 3.2.4。

The code itself hasn't changed.代码本身没有改变。

C#: C#:

public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
    var reject = false;
    var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;

    if (principal == null || !principal.Identity.IsAuthenticated || reject) {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
            new { error = "Unauthorized request for Impersonate Mode" },
            actionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
        return Task.FromResult<object>(null);
    }

    return Task.FromResult<object>(null);
}

Typescript:打字稿:

actionErrorResponseHandler(response: Response) {
    if(response.status === 401){
        if(response.text().includes("Impersonate")){
            this.displayText = ImpersonateRejectText;
        }
        this.show();
    }
}

(EDIT) Called like so: (编辑)这样调用:

setupPopUpModal(modalHeader: string, displayText: string){
    this.accountService.accountShowPopUpModal()
    .pipe(catchError((response: Response) => this.rejectModal.actionErrorResponseHandler(response)))
    .subscribe((result: string) => {
        if(result == "Done"){
            this.modalHeader = modalHeader;
            this.displayText = displayText;
            this.messageBoxModal.show();
        }            
    })
}

Previously this worked fine.以前这工作正常。 Now it generates an error that says "e.text is not a function"现在它会生成一个错误,指出“e.text 不是函数”

If I look in Chrome's dev tools I see this from before the upgrade:如果我查看 Chrome 的开发工具,我会在升级前看到这一点:

前

And this afterwards:这之后:

后

The .text() function is trying to return the body as a string, but the body does not exist anymore. .text() 函数试图将正文作为字符串返回,但正文不再存在。 The message I'm trying to search is now in e.error, but in Angular/Typescript "response.error" is not valid code.我试图搜索的消息现在在 e.error 中,但在 Angular/Typescript 中“response.error”不是有效代码。

I'm assuming I need to build and/or parse the response differently but I've not been able to find any documentation on this.我假设我需要以不同的方式构建和/或解析响应,但我找不到任何关于此的文档。 Any help would be much appreciated.任何帮助将非常感激。

I would assume that the old Angular version was prior to 4.3 ?我会假设旧的 Angular 版本在 4.3 之前?

With 4.3 the regular HTTP request changed from "Http" to "HttpClient".在 4.3 中,常规 HTTP 请求从“Http”更改为“HttpClient”。 The main change is that you do not get the response as a result, but only the (json) response body.主要的变化是你没有得到响应结果,而是只有 (json) 响应正文。 And if the request was not a success (and a 401 isn´t one :-) ), than it errors out.如果请求不成功(并且 401 不是一个 :-) ),那么它就会出错。

Therefor you have to catch the error and handle it.因此,您必须捕获错误并处理它。 This can be done multiple ways.这可以通过多种方式完成。 I would assume that you use RxJs to handle the response.我假设您使用 RxJs 来处理响应。 Then your code may look like that那么你的代码可能看起来像这样

let response: SomeTyp;
this.httpClient.get<SomeTyp>('myBackendUrl').subscribe( (result) => response = result);

As a result, if your backend call returns a 400, the "regular" subscription will not be executed.因此,如果您的后端调用返回 400,则不会执行“常规”订阅。 Therefor response stays empty.因此response保持为空。

One solution could be to handle the error case in the subscribe一种解决方案可能是处理订阅中的错误情况

let response: SomeTyp;
this.httpClient.get<SomeTyp>('myBackendUrl').subscribe( 
  (result) => response = result,
  (errorCase) => this.handleTheError(errorCase)
);

private handleTheError(errorCase:ttpErrorResponse):void {
  if(response.status === 401){
    if(response.text().includes("Impersonate")){
      this.displayText = ImpersonateRejectText;
      return
    }
  }
  throw Error('Unexpected Backend Response');
}

A second solution would be to handle it in the stream第二种解决方案是在流中处理它

let response: SomeTyp;
this.httpClient.get<SomeTyp>('myBackendUrl').pipe(
  catchError( (errorCase:ttpErrorResponse) => // Handle the error )
).subscribe( 
  (result) => response = result
);

The advantage of "catchError" is, that you can catch the error and if it is an "expected" error that you can handle gracefully, just return a valid value. “catchError”的优点是,您可以捕获错误,如果它是您可以优雅处理的“预期”错误,只需返回一个有效值。 Then this value will be handled by the subscribe exactly like when you would have get a valid backend response.然后这个值将由订阅处理,就像您获得有效的后端响应一样。
If the error is NOT possible to handle gracefully, you can still throw it again如果错误无法正常处理,您仍然可以再次抛出它

return throwError(errorCase);

And then handle it in the subscribe.然后在订阅中处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM