2017-11-14 4 views
0

Wie feuern Funktion, die Back-End-Daten benötigt? Mein Ziel ist es getPersons() abzufeuern, die 4. auf getCities() und getCars() mit kantigem hängtAngular 4 fire-Funktion nach Serverdaten geladen

export class Person { 
    constructor(
    public cities: any[], 
    public cars: any[] 
) { } 
} 

In Komponente nenne ich:

public ngOnInit(): void { 
    this.getCars(); 
    this.getCities(); 
    this.getPersons(); 
    } 

EDIT Service:

public getCars(): Observable<CarsList> { 
    return this.http.get(this.carsUrl) 
     .map((res: Response) => res.json()) 
     .catch((error: Response) => Observable.throw(
     this.errorHandlerService.showError(getCarsError))); 
    } 

Component :

public getPersons(): void { 
    this.personsService.getPersons() 
     .subscribe(
      (data) => { 
      this.persons = data; 
      this.persons .forEach((person, index) => { 
       person.carName = this.cars.find((car) => car.id === person.carId).name; 
       console.log('error here because this.cars is still undefined') 
      } 
     ) 
} 

Problem ist, dass getPersons() gefeuert wird, bevor getCities() und getCars() geladen werden und Daten hängt davon ab. So this.cities oder this.cars Objekte sind null und App-Absturz. Wie wird getPersons() ausgelöst, wenn getCities() und getCars() geladen sind? Bereits versucht AfterViewInit mit setTimeout Problemumgehungen, die nicht funktionieren.

+0

Wie sind sie verwandt? Sind sie asynchron? – briosheje

+0

Bitte zeigen Sie den Code 'getCars()', 'getCities()' und 'getPersons()'. –

+0

aktualisiert hinzugefügt Dienst und Komponente – TeodorKolev

Antwort

0

auf diese Weise gelöst: Service:

public async getCars(): Promise<DetailedObjectsList> { 
    try { 
     const response = await this.http.get(this.carsUrl).toPromise(); 
     return response.json(); 
    } catch (e) { 
     this.errorHandlerService.showError(carsError); 
    } 
    } 

Komponente:

public async getCars() { 
    await this.carsService.getCars() 
     .then((data) => { 
     if (!isNullOrUndefined(data)) { 
      this.cars = data.detailedObjects; 
     } 
     }); 
    } 

und am wichtigsten:

public ngOnInit(): void { 
    this.getCars() 
     .then(() => { 
     this.getCities() 
      .then(() => { 
      this.getPersons(); 
     }); 
     }); 
    } 

Ich hoffe, dass auch für Sie hilft.