Angular Universal Platform Check

최대 1 분 소요

Checking whether the platform Angular is running on is a browser or a server.

The reason for checking is that if Angular is running on a server platform, commands that are only available in the browser, such as window, location, and document, cannot be used.

This post assumes that an Angular Universal project is already set up, so please refer to Angular Universal for how to apply Angular Universal.

Principle

When the project is executed, a PLATFORM_ID is generated, which can be passed as a parameter to the isPlatformBrowser and isPlatformServer functions supported by @angular/common to determine the platform.

Component

import { OnInit, Component, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.html'
})
export class AppComponent implements OnInit {
	isBrowser: boolean = false;
	isServer: boolean = false;

  constructor(
	@Inject(PLATFORM_ID) private platformId: object
  ) {

  }

  ngOnInit() {
	if(isPlatformBrowser(this.platformId)) this.isBrowser = true;
	if(isPlatformServer(this.platformId)) this.isServer = true;
  }
}

Template

<p>isPlatformBrowser: <span></span></p>
<p>isPlatformServer: <span></span></p>

Now, running the application will show on which platform it is being executed.

End.

댓글남기기