1
我們有一個使用angular/cli的簡單Angular通用應用程序:1.4.3 (和node:6.9.5)。Angular Universal - 如何手動觸發從服務器端到客戶端視圖的狀態更改?
我們設法配置服務器端視圖。當dom準備就緒時,我們切換到客戶端視圖。但是,在我們收集API所需的所有數據之前就已經完成了切換。因此,在頁面顯示沒有數據的情況下,切換之後有一段時間。
有沒有辦法手動觸發2個狀態之間的切換?在這種情況下,我們希望在從API獲取響應後顯示客戶端視圖。
這是我們對本作的簡單的例子:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Response, Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'home',
templateUrl: 'home.component.html',
styleUrls: [
'./styles/glh.css'
]
})
export class HomeComponent implements OnInit{
public hotel: any;
public id: number = null;
constructor(
public http: Http,
private route: ActivatedRoute
) {
}
ngOnInit() {
this.route.params.subscribe((params: any) => {
this.id = params.id;
if(this.id) {
this.getHotel(this.id).subscribe(hotel => {
this.hotel = hotel;
});
}
});
}
private getHotel(hotelId: number): Observable<any> {
return this.http.get(`https://api.example.com/v1/example/${hotelId}`)
.map(this.extractData)
.map((data: any) => {
return data;
});
}
protected extractData(res: Response) {
return res.json() || { };
}
}
謝謝!
好主意!我們現在正在嘗試,我會讓你知道結果。 –
我們做了同樣的工作,所以它的工作原理:)儘管如此,我們另外還在SSR文件中傳輸API數據(所以API在服務器端被調用,結果被寫入.html文件,以便客戶端可以直接讀取它,而無需其他API調用) – Moema
謝謝!它爲我們工作!這是完美的答案:-) –