问题
We have a simple Angular Universal app using angular/cli: 1.4.3 (and node: 6.9.5).
We manage to configure the server side view. When the dom is ready, we switch to a client view. But, the switch is made before we collect all the data needed from the API. So there is a moment right after the switch when the page is displayed without the data.
Is there any way to trigger manually the switch between the 2 states? In this case, we want to display the client view after we get the response from the API.
Here is the simplified example we made for this:
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() || { };
}
}
Thanks!
回答1:
You can use Angular's route resolver to avoid the blink. See Angular Routing docs for more information.
If you fetch your data in the resolver, Angular will only route to your component (and initialize it) when the data is already there. Since the switch happens after everything is initialized, it is absolutely smooth and without any blink.
来源:https://stackoverflow.com/questions/46471986/angular-universal-how-to-trigger-manually-the-state-change-from-server-side-to