我在实现一项服务时遇到问题,该服务加载一次数据(gyms 数组),然后允许所有其他组件使用它,而不发出其他 HTTP 请求。
如果用户从标题页开始并加载所有数据,我的应用程序工作正常,但是当我转到特定详细信息页面 (.../gym/1) 并重新加载页面时,该对象不在服务阵列还没有。如何让尝试访问服务数组的组件等待数据加载?更具体地说,如何延迟 GymComponent 中对gymService.getGym(1) 的调用,直到 getAllGymsFromBackEnd() 函数完成填充数组?
我读过有关解析器的内容,但我的修改毫无结果。
如有任何帮助,我们将不胜感激。
这是我正在编写的代码:
服务:
import {Injectable} from "@angular/core";
import {Gym} from "../objects/gym";
import {BaseService} from "./base.service";
import {Http, Response} from "@angular/http";
import {HttpConstants} from "../utility/http.constants";
@Injectable()
export class GymService extends BaseService {
private gyms: Gym[] = [];
constructor(protected http: Http, protected httpConstants: HttpConstants) {
super(http, httpConstants);
this.getAllGymsFromBackEnd();
}
getAllGymsFromBackEnd() {
return super.get(this.httpConstants.gymsUrl).subscribe(
(data: Response) => {
for (let gymObject of data['gyms']) {
this.gyms.push(<Gym>gymObject);
}
}
);
}
getGyms() {
return this.gyms;
}
getGym(id: number) {
return this.gyms.find(
gym => gym.id === id
)
}
}
组件:
import {Component, OnDestroy, AfterViewInit, OnInit} from "@angular/core";
import {ActivatedRoute} from "@angular/router";
import {Subscription} from "rxjs";
import {Gym} from "../../objects/gym";
import {GymService} from "../../services/gym.service";
declare var $:any;
@Component({
selector: 'app-gym',
templateUrl: './gym.component.html',
styleUrls: ['./gym.component.css']
})
export class GymComponent implements OnInit, OnDestroy, AfterViewInit {
private subscription: Subscription;
private gym: Gym;
constructor(private activatedRoute: ActivatedRoute,
private gymService: GymService
) {}
ngOnInit(): void {
this.subscription = this.activatedRoute.params.subscribe(
(param: any) => {
this.gym = this.gymService.getGym(parseInt(param['id']));
}
);
}
ngAfterViewInit(): void {
$( document ).ready(function() {
$('.carousel').carousel();
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
最佳答案
您可以使用Resolver
以及。在这里查看 https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html或者使用可观察的。所以private gym: Gym;
将变成private gym$:Observable<Gym>;
,并在您的模板中使用 async
通过管道获取数据。
关于javascript - Angular2 - 让组件等待服务完成数据获取,然后渲染它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193922/