Angular Universal - How to trigger manually the state change from server side to client view?

假如想象 提交于 2020-01-02 18:57:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!