【问题标题】:Can't loop through an array of objects in Typescript (Angular)无法遍历 Typescript (Angular) 中的对象数组
【发布时间】:2022-01-08 19:00:29
【问题描述】:

在我的项目中,我从 API(行程实体)获取数据。这是我的模型:

  //Trip.model.ts
  export class Trip{
  created_at?:Date;
  updated_at?:Date;
 .... bunch of fields
}

在我的组件中,我正在获取数据并将其分配给 trips 变量。但是,当我尝试访问 trips 数组中的任何项目时,我得到“未定义”。我也无法遍历它,我尝试了 forEachfor...in/of
我尝试使用接口而不是类,但没有运气。如何遍历该对象数组以使用其中的数据?
组件代码:

  userName:string='';
  trips:Trip[]=[];
  moment:any=moment;
  usersData:any={};

  constructor(private auth: AuthService,
              private storage: LocalStorageService,
              private translate: TranslateService,
              private tripService: TripService){}

    ngOnInit(): void {
    console.log(this.translate.currentLang)
    this.userName=localStorage.getItem('username')!;
    this.fetchTrips();
    this.fetchPics();
  }

  fetchTrips() {
    this.tripService.getTrips().subscribe({
      next: data => {
        data[0].data.forEach((value) => {
          let trip: Trip = plainToInstance(Trip,value);
          this.trips.push(trip);
        });
      }, error: error => {
        console.log(error);
      }
    });
  }
  //fetchPics because I want to extract 
  //user's profile pics' urls from the trips array
  fetchPics(){
    console.log(this.trips);
    console.log(this.trips[0]);
    this.trips.forEach((trip)=>{
      console.log(trip);
    });
  }

getTrips 服务方法:

getTrips(){
    return this.http.get<any>(Api.API+Endpoints.TRIP);
  }

这是当我显示的时候

console.log(this.trips)

分配后。

来自 API 的数据:

裁剪图片以使其更具可读性。

【问题讨论】:

  • 您的 Trip 模型显示的是对象,而不是数组?
  • 您能举例说明 getTrips sub 返回的内容吗?此外,您的代码中还有一些其他问题,但让我们将其留到下一步。
  • @MikeOne 刚刚编辑了它显示的内容,它是一个数组,对吧?
  • @MishaMashina 刚刚添加,您是这个意思吗?

标签: javascript angular typescript angular-components


【解决方案1】:

您试图在实际拥有数据之前访问 this.trips 值。这是因为您异步获取该数据,就在 this.tripService.getTrips() 的订阅中

所以,为了解决你的问题,你只需要移动这个调用:

 this.fetchPics();

在 fetchTrips() 方法的 subscribe 里面,像这样:

fetchTrips() {
    this.tripService.getTrips().subscribe({
      next: data => {
        data[0].data.forEach((value) => {
          let trip: Trip = plainToInstance(Trip,value);
          this.trips.push(trip);

          this.fetchPics();

        });
      }, error: error => {
        console.log(error);
      }
    });
  }

【讨论】:

    【解决方案2】:

    函数fetchPics() 在您的getTrips 调用结束之前执行。只有在 HTTP 调用结束并且成功填充 trips 数组后,您才需要调用该方法。

    fetchTrips() {
        this.tripService.getTrips().subscribe({
          next: data => {
            //Populate your trips array
            data[0].data.forEach((value) => {
              let trip: Trip = plainToInstance(Trip,value);
              this.trips.push(trip);
            });
            // this is where you need to call
            this.fetchPics(); 
          }, error: error => {
            console.log(error);
          }
        });
      }
    

    【讨论】:

      【解决方案3】:

      这是因为 JS 是异步的。您在这里发出 http 请求,这可能需要一些时间才能从服务器获取数据。让我们假设可能需要 1 分钟,然后编译器不会停止它的执行过程,在那 1 分钟的时间内,它将执行下一个语句。因为 您的 fetchpics() 方法在 fecthtrips() 执行完成之前执行强>。为了克服这个问题,我们可以使用 async, await 如下所示。

      async fetchTrips() {
          this.tripService.getTrips().subscribe({
            next: data => await {
              data[0].data.forEach((value) => {
                let trip: Trip = plainToInstance(Trip,value);
                this.trips.push(trip);
              });
        }, error: error => {
          console.log(error);
        }
      });
      

      }

      【讨论】:

        猜你喜欢
        • 2020-03-29
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 2020-01-18
        • 2017-11-20
        • 1970-01-01
        • 2021-08-27
        相关资源
        最近更新 更多