2017-09-28 11 views
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() || { }; 
    } 
} 

謝謝!

回答

2

您可以使用Angular的路由解析器來避免眨眼。有關更多信息,請參閱Angular Routing docs

如果您在解析器中獲取數據,那麼當數據已經存在時,Angular將僅路由到您的組件(並初始化它)。由於開關在所有事件初始化後都會發生,因此絕對平穩且沒有任何眨眼。

+0

好主意!我們現在正在嘗試,我會讓你知道結果。 –

+0

我們做了同樣的工作,所以它的工作原理:)儘管如此,我們另外還在SSR文件中傳輸API數據(所以API在服務器端被調用,結果被寫入.html文件,以便客戶端可以直接讀取它,而無需其他API調用) – Moema

+0

謝謝!它爲我們工作!這是完美的答案:-) –

相關問題