简体   繁体   English

Angular 组件未从服务获取正确数据

[英]Angular Component not getting proper data from Service

I think I understand the issue I am having, yet am having a hard time figuring out the best solution.我想我理解我遇到的问题,但很难找出最佳解决方案。 I have an Ionic / Angular app which makes API calls through a variety of Service classes, all of these Service classes are called by a parent "DataService" class.我有一个 Ionic / Angular 应用程序,它通过各种服务类进行 API 调用,所有这些服务类都由父“DataService”class 调用。

Once a user logs into my application, they are redirected to a "TaskList" component.一旦用户登录到我的应用程序,他们就会被重定向到“TaskList”组件。 This component calls DataService.getData() which should populate several arrays within DataService with the appropriate data.该组件调用DataService.getData() ,它应该使用适当的数据填充 DataService 中的几个 arrays。 This code can be seen below:这段代码可以在下面看到:

export class TaskListPage implements OnInit {
    ...
    ngOnInit() {
    this.dataService.getData().then(() => {
      this.workOffers = this.dataService.getWorkOffers();
      this.confirmedWorkOrderDates = this.dataService.getConfirmedWorkOrderDates();
      console.log("Client Task List WO: " + JSON.stringify(this.workOffers));
    });
  }
}

However, upon the page being loaded, the workOffers array is empty [] as can be seen from the console.log line.但是,在加载页面后,workOffers 数组为空 [],从 console.log 行可以看出。

I know this is because the TaskListPage is somehow calling DataService.getWorkOffers() before DataService has had a chance to store any daya within that array.我知道这是因为TaskListPage 在DataService 有机会在该数组中存储任何daya 之前以某种方式调用DataService.getWorkOffers()。 I've tried adding promises to the getData function to force the execution of getWorkOffers() to happen after getData is done executing, but it doesn't work.我尝试向 getData function 添加承诺,以强制在 getData 执行完成后执行 getWorkOffers(),但它不起作用。

Here is DataService.getData():这是 DataService.getData():

getData() {
    return new Promise<void>((resolve) => {
      this.workOffers = new Array();
      this.updates = new Array();
      this.tasks = new Array();
      this.shifts = new Array();
      this.confirmedWorkOrderDates = new Array();
      // Get USER object of user logged in
      this.userService.getUser(this.currentUserId).subscribe(async (user: User) => {
        this.userLoggedIn = user;
        this.currentUserId = user.id;
  
       
        this.getClientData().then(() => {
            resolve();
        });
        }
      });
    });
  }

getClientData is another method that calls several other service classes: getClientData 是另一种调用其他几个服务类的方法:

getClientData() {
    return new Promise<void>((resolve) => {
      this.workOfferService.getClientBookedOffers(this.currentUserId)
        .subscribe((workOffers: WorkOffer[]) => {
          for (let wo in workOffers) {
            // Push workOffer to array
            this.workOffers.push(workOffers[wo]);
            ...[ More Service calls]
          }
        });
        resolve();
    });
  }

I must be using the Promises incorrectly, because from what I understand getData should finish executing (and thus populate DataService.workOffers[]) before TaskList calls getWorkOffers.我一定是错误地使用了 Promises,因为据我了解 getData 应该在 TaskList 调用 getWorkOffers 之前完成执行(并因此填充 DataService.workOffers[])。

I don't know what is the Angular version that you're using here.不知道你这里用的Angular版本是什么。 In my opinion it could be simplified using just an Obversable e2e.Angular HttpService already provides this in newest versions.在我看来,它可以简化使用 Obversable e2e.Angular HttpService 已经在最新版本中提供了这个。

It seems to me that you're resolving the promise on getClientData to soon.在我看来,您很快就会解决 getClientData 上的 promise 问题。 When you're calling resolve ouside of the subscribe, so GetClientData Promise are returning with WorkOffer empty.当您在订阅之外调用 resolve 时,GetClientData Promise 将返回 WorkOffer 为空。

A small example of what I'm trying to explain https://stackblitz.com/edit/angular-ivy-weug88?file=src/app/app.component.ts我试图解释的一个小例子https://stackblitz.com/edit/angular-ivy-weug88?file=src/app/app.component.ts

This should fix you're use case:这应该可以解决您的用例:

getClientData() {
    return new Promise<void>((resolve) => {
      this.workOfferService.getClientBookedOffers(this.currentUserId)
        .subscribe((workOffers: WorkOffer[]) => {
          for (let wo in workOffers) {
            // Push workOffer to array
            this.workOffers.push(workOffers[wo]);
            ...[ More Service calls]
          }
          
          // now only resolve when WorkOffer are fully loaded
          resolve();
        });
    });
  }

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

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