如何在Angular 4中检查isBrowser [英] How to check for isBrowser in Angular 4

查看:92
本文介绍了如何在Angular 4中检查isBrowser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去你可以使用Angular Universal的 isBrowser 来检查你的页面是否在浏览器中呈现(因此你可以使用像localStorage这样的东西),或者它是否是做服务器端预渲染。

In the past you could use isBrowser from Angular Universal to check if your page was rendering in a browser (and therefore you can use things like localStorage) or if it was doing server side pre-rendering.

但似乎 angular2-universal 已解散为 @ angular / core @ angular / platform-server @ angular / platform-b​​rowser

我在Angular 4的API文档中寻找类似的功能,并试图在源代码的某处找到它,但没有运气。

I've looked for similar functionality in the API documentation for Angular 4 and also tried to find it somewhere in the source code, but without luck.

我是否遗漏了某些东西,或者Angular 4检查渲染是否在浏览器中运行的方式是什么?或者我应该只检查是否定义了窗口

Am I missing something or what is the Angular 4 way of checking if the rendering is running in a browser? Or should I simply just check if window is defined?

推荐答案

import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';
...
export class MyComponent {
...
    testBrowser: boolean;
    constructor(
        @Inject(PLATFORM_ID) platformId: string) {
            this.testBrowser = isPlatformBrowser(platformId);
            if (this.testBrowser) {
                //this is only executed on the browser
            }
    }
...

这篇关于如何在Angular 4中检查isBrowser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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