.NET Core 5.0 - Angular 9 - 如何在维护 MVC/json 映射的同时获取 HTTP return 代码?

.NET Core 5.0 - Angular 9 - how to get HTTP return code while maintaining MVC/json mapping?

上下文:Angular9 向 .NET Core 5.0 请求数据API

我尝试观察 http return 代码,所以我添加了 {observe: "response"}

getLoggedUserInfos(singlePost:SinglePost) {
    return this.http.post<UserFetch>(this.appConfigService.getConfig()["apiUrl"] + 'api/Users/loggedUserInfos',singlePost,{observe: "response"});
}

但从那以后,我的代码就无法编译了

this.getLoggedUserInfos(singlePost).subscribe((userFetch:UserFetch)=>{
...

没有与此调用匹配的重载。

我该如何解决这个问题?

感谢您的帮助

[编辑]

map 和 catchError 似乎没有定义

getLoggedUserInfos(singlePost:SinglePost) {
    return this.http.post<UserFetch>(this.appConfigService.getConfig()["apiUrl"] + 'api/Users/loggedUserInfos',singlePost,{observe: "response"})
    .pipe(
        map(response => response as UserFetch),
        catchError((err) => {
           console.error(err);
           throw err;
        })
    );
  }

IIRC,类型断言 {observe: "response"} 没有重载。尝试使用 RxJS map operator

断言
import { map, catchError } from 'rxjs/operators';

getLoggedUserInfos(singlePost:SinglePost): Observable<UserFetch> {
  return this.http.post(
    this.appConfigService.getConfig()["apiUrl"] + 'api/Users/loggedUserInfos',
    singlePost,
    { observe: "response" }
  ).pipe(
    map(response => response as UserFetch) // <-- possibly error prone
  );
}

并且由于您现在获得了整个响应,因此来自 map 运算符的 return 变量必须是 response 变量的某些 属性。

编辑:添加导入。

我不明白你的目标到底是什么,如果你想以不同的方式处理错误代码,有比自己通过响应查看状态代码更好的选择 (https://angular.io/guide/http#error-handling)。

你得到一个编译错误,因为 post 方法 returns HttpResponse<UserFetch> 所以订阅时,它不是 UserFetch 类型,而是 HttpResponse<UserFetch> ].当你真的想查看状态代码时,你可以在那里查看。

this.getLoggedUserInfos(singlePost).subscribe(response => {
  console.log(response.status);
  const userFetch = response.body;
});

我会推荐使用catchError,有很好的例子。