Angular 2+ and Entity Framework : 无法通过 Id 获取对象,returns 一个空数组

Angular 2+ and Entity Framework :Cannot get objects by Id, returns an empty array

我在获取属性 userID 等于我从另一个 HTTP 请求获取的参数的 Wall 对象时遇到问题。获取所有墙的请求成功,但是当我传递 userID 时,它 returns 是一个空数组。我正在使用 Entity Framework 作为后端。我已经在 Postman 中测试了该请求并且它有效。

控制器:

[HttpGet("GetWallsByUserId/{userId}")]
       public async Task<ActionResult<IEnumerable<Wall>>> GetWallsByUserId(string userId) 
       {
           return await _context.Walls.Where(w => w.userID == userId).ToListAsync();
       }

服务代码:

getQuizByUserId(id:any){
    return this.http.get<any>(this.BaseURI+'/Wall/GetWallsByUserId/'+id).pipe(
      catchError(Error=>of(null))
    );

在组件中,我正在获取当前登录用户的 ID,并传递该 ID 以获取具有该 ID 的所有 Wall 对象:

userID:any;
userDetails;
walls=[];
ngOnInit(): void {
   this.userService.getUserProfile().subscribe(
     res=>{
       this.userDetails=res;
        this.userID=this.userDetails.id;
        console.log(this.userID);
     }
   );
     this.service.getQuizByUserId(this.userID).subscribe(
       res=>{
         this.walls=res;
         console.log(res);
       }
     )
}

}

我真的不知道我错过了什么,在控制台中 userId 总是成功返回,但 res 和 walls 总是空数组。这是获取所有墙的成功请求:

 getAllWalls()//getting all the wall in home component
  {
    return this.http.get<any>(this.BaseURI+'/Wall');
  }

c# 代码是同步的,而 javascript 是异步的。你得到 this.userId 太晚了。如果您调试代码,您会看到调用 this.service.getQuizByUserId(this.userID) 时使用的是未定义的,而不是 userId。要解决这个问题,请尝试以正确的方式使用 rxjs。可能的解决方案:

  this.userService.getUserProfile().pipe(
     switchMap(res => {
       this.userDetails = res;
       this.userID = this.userDetails.id;
       return this.service.getQuizByUserId(this.userID)
     })
  ).subscribe(res => {
      this.walls = res;
      console.log(res);
   })

在您的 pipe 中,您还应该 map 内容,如下所示:

getQuizByUserId(id:any){
    return this.http.get<any>(this.BaseURI+'/Wall/GetWallsByUserId/'+id).pipe(
        map((res: any) => {
        return res;
      }),
      catchError((error: any) => { return throwError(error); })
    );

当你订阅你的服务时,ts 不等待响应它继续执行其他代码。在您的服务收到数据后,res=>{} 块运行。

在 console.log(this.userID) 之前调用此代码块。您可以将其设为函数并在 console.log(this.userID)

之前调用
this.service.getQuizByUserId(this.userID).subscribe(
   res=>{
     this.walls=res;
     console.log(res);
   }
 )