【问题标题】:Angular 2+ and Entity Framework :Cannot get objects by Id, returns an empty arrayAngular 2+ 和实体框架:无法通过 Id 获取对象,返回一个空数组
【发布时间】:2020-07-27 07:28:46
【问题描述】:

我在获取属性 userID 等于从另一个 HTTP 请求获得的参数的 Wall 对象时遇到问题。获取所有墙壁的请求成功,但是当我传递用户 ID 时,它返回一个空数组。我使用实体框架作为后端。我已经在 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 和 wall 总是空数组。这是获取所有墙壁的成功请求:

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

【问题讨论】:

    标签: angular entity-framework httprequest


    【解决方案1】:

    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);
       })
    

    【讨论】:

    • 我认为我没有正确发送该 ID,并且我的方法可能是错误的。谢谢大佬。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      在您的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); })
          );
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-18
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多