Shadov
Shadov

Reputation: 33

.NET Angular how to get data asynchronously

First I'm trying to get all projects from the database by given userId from URL. I'm doing it in ngOnInit(). Each project has it's field Languages which is a list of objects from another table Languages. One record in this table has a field named projectId by which I'm trying to get all languages for each project. I think I have a problem with receiving data asynchronously because projects are received properly but languages field in each Project object is null. What should I do?

ngOnInit() {
    this.userId = this.route.snapshot.params['id'];
    this.getAllProjectsByUserId(this.userId);
    this.getLanguagesByProjectId();
  }

  getAllProjectsByUserId(id: number) {  //receivng all projects for given userId
    this.portfolioAppService.getAllProjectsByUserId(id).subscribe((data) => {
      this.projectsList = data;
      console.log(this.projectsList);
    },
      error => console.error(error)
    );
  }

  getLanguagesByProjectId() {  //receiving all languages for each project
    this.projectsList.forEach(x => {
      this.portfolioAppService.getLanguagesByProjectId(x.id).subscribe((data) => {
        x.languages = data;
        console.log(this.projectsList);
      },
        error => console.error(error)
      );
    });
  }

Upvotes: 1

Views: 54

Answers (1)

jeprubio
jeprubio

Reputation: 18002

Move the call to getLanguagesByProjectId() to when the projects have been received:

  getAllProjectsByUserId(id: number) {  //receiving all projects for given userId
    this.portfolioAppService.getAllProjectsByUserId(id).subscribe((data) => {
      this.projectsList = data;
      console.log(this.projectsList);
      this.getLanguagesByProjectId();
    },
      error => console.error(error)
    );
  }

As otherwise this.projectsList property has not the needed values yet.

Upvotes: 2

Related Questions