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

查看:35
本文介绍了如何在 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@角度/平台浏览器.

But it seems that angular2-universal was dissolved into @angular/core, @angular/platform-server and @angular/platform-browser.

我在 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 方法是什么?或者我应该只是检查是否定义了 window?

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