我無法實現加載數據服務(體育館陣列)一次,然後讓所有其他組件來使用它,而不進行其他HTTP要求。Angular2 - 將分量等到服務完成讀取數據,然後渲染它
我的應用程序工作正常,如果用戶開始在扉頁和加載的所有數據,但是當我去到一個特定的詳細信息頁面(... /體育館/ 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();
}
}
您的服務應該公開可觀察到的事物能*訂閱*到。例如,您可以使用'ReplaySubject'來充當緩存。讓'getGyms'返回'Observable'。 –
jonrsharpe
感謝您的回覆,我按照您的建議進行了更改。你可以看一看,看看我做得對嗎?我也不知道如何實現getGym(id)函數並在組件中使用它,你可以幫忙嗎? – Vodyara
在吸引回答後不要更改問題。如果你想知道你是否做得對,請測試它! – jonrsharpe