I have a data.service.ts where I want to preload 2 arrays:
public aspects: DTO.Aspect[];
public reports: DTO.Report[];
constructor(dao: DaoService){
// Getting Reports
this.dao.getReports().subscribe(reps: DTO.Report[] => {
this.reports = reps;
})
//Getting Aspects of each Report
for(let i = 0; i < this.reports.length; i++){
this.dao.getAspects(this.reports[i].reportId).subscribe(asps: DTO.Report[] => {
this.aspects = asps;
})
}
}
FYI dao.service.ts
import { Injectable } from "@angular/core";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError, retry } from "rxjs/operators";
import { DTO } from "./dto";
@Injectable({
providedIn: "root"
})
export class Dao {
private static API: String =
"https://apiapiapiapi.com";
constructor(private http: HttpClient) {}
getAspects(repId: string): Observable<DTO.Aspect[]> {
console.log(Dao.API + "aspect/report/" + repId);
return this.http
.get<DTO.Aspect[]>(Dao.API + "aspect/report/" + repId)
.pipe(retry(3), catchError(this.handleErrors));
}
getReports(): Observable<DTO.Report[]> {
console.log(Dao.API + "report/current");
return this.http
.get<DTO.Report[]>(Dao.API + "report/current")
.pipe(retry(3), catchError(this.handleErrors));
}
}
After that I want to use these arrays everywhere in my app. For Example when I click in the sidebar on a report it should route me to a page where all the aspects of that report are displayed:
report.component.ts
routerLink: localhost:4200/report/512
import { Component, OnInit } from "@angular/core";
import { Router, ActivatedRoute, ParamMap } from "@angular/router";
import { DataService } from "@core/data.service";
import { DTO } from "@core/dto";
import { Dao } from "@core/dao.service";
@Component({
selector: "app-report",
template: "<div *ngFor='let aspect of aspects'>
<span>{{aspect.aspectName}}</span>
</div>",
styleUrls: ["./report.component.scss"]
})
export class ReportComponent implements OnInit {
aspects: DTO.Aspect[] = [];
constructor(data: DataService, route: ActivatedRoute){
// Get the Report ID from the URL
this.route.paramMap.subscribe(params => {
const reportId = params.get("reportId");
// Use the Report ID (512) as parameter to find the Aspects of this Report
this.aspects = this.data.aspects.filter(aspect => { // aspects in data.service.ts are not loaded yet
return aspect.reportId == reportId;
})
})
}
}
The problem is that the aspects in the data.service.ts are not necessarely loaded yet. I tried a few things by creating my own Observers or using Promises but the performance became even worse. So my question is:
How can I load data once and use them when they are ready?