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

查看:73
本文介绍了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的路由解析器来避免眨眼.有关更多信息,请参见角路由"文档.

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天全站免登陆