【发布时间】:2019-12-19 23:12:34
【问题描述】:
我有一个 data.service.ts 我想在其中预加载 2 个数组:
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;
})
}
}
仅供参考 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));
}
}
之后我想在我的应用程序的任何地方使用这些数组。例如,当我单击报告的侧边栏时,它应该将我引导到显示该报告所有方面的页面:
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;
})
})
}
}
问题是 data.service.ts 中的方面还没有加载。我通过创建自己的观察者或使用 Promises 尝试了一些事情,但性能变得更糟。所以我的问题是:
我怎样才能加载数据一次并在它们准备好时使用它们?
【问题讨论】:
-
请粘贴您的 dao 服务
-
你的订阅调用是假的,应该是 this.dao.getReports().subscribe(reps => this.reports = reps);这段代码还能编译吗?
-
@mwe 你是对的。我将此代码作为当前问题的示例输入到我的 stackoverflow 文章中。我刚刚编辑了它。
-
您可以将数据缓存在 localStor 或 sessionStore 中。
-
@PedroB。我不知道在这种情况下你需要什么 dao 服务,但我在文章中添加了它。只有 2 个方法返回 observables。当给定reportId作为参数时,一个带有报告,一个带有方面
标签: angular typescript