Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - How to check for isBrowser in Angular 4

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.

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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
            }
    }
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...