Angular Universal - 如何手动触发从服务器端到客户端视图的状态变化? [英] Angular Universal - How to trigger manually the state change from server side to client view?

查看:23
本文介绍了Angular Universal - 如何手动触发从服务器端到客户端视图的状态变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用 angular/cli 的简单 Angular Universal 应用程序:1.4.3(和节点:6.9.5).

We have a simple Angular Universal app using angular/cli: 1.4.3 (and node: 6.9.5).

我们设法配置了服务器端视图.当 dom 准备好时,我们切换到客户端视图.但是,切换是在我们从 API 收集所需的所有数据之前进行的.所以在没有数据的情况下显示页面时,在切换之后有一个时刻.

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.

有没有办法手动触发两种状态之间的切换?在这种情况下,我们希望在从 API 获得响应后显示客户端视图.

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() || { };
    }
}

谢谢!

推荐答案

你可以使用 Angular 的路由解析器来避免眨眼.有关详细信息,请参阅 Angular Routing 文档.

You can use Angular's route resolver to avoid the blink. See Angular Routing docs for more information.

如果您在解析器中获取数据,Angular 只会在数据已经存在时路由到您的组件(并对其进行初始化).由于切换发生在一切初始化之后,所以绝对流畅,没有任何闪烁.

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.

这篇关于Angular Universal - 如何手动触发从服务器端到客户端视图的状态变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆