角度对PLATFORM_ID的isPlatformBrowser检查不会阻止服务器端预渲染

Mic*_*bro 6 angular-universal angular

我正在尝试编译这里基于示例项目创建的Angular 4 + ASP.NET Universal应用程序,使用此提示https://github.com/angular/universal#universal-gotchas 以及当我使用webpack构建项目时,然后运行它如果检查了块,则封装在其中的代码将引发错误

isPlatformBrowser

已在服务器端呈现。如何在不进行预渲染的情况下在客户端有效地强制执行此代码,而其他与服务器端预渲染正常工作的代码却要在服务器端进行预渲染?

这是我的组件,其传单代码封装在条件块中,用于检查平台是否为浏览器。

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


@Component({
    selector: 'leaflet-map',
    templateUrl: 'leaflet-map.component.html',
    styleUrls: ['leaflet-map.component.css', '../../../..//node_modules/leaflet/dist/leaflet.css'],
})
export class LeafletMapComponent implements OnInit { 

    constructor(@Inject(PLATFORM_ID) private _platformId: Object) {  }

    ngAfterViewInit() { 


    }

    ngOnInit() {  
        if (isPlatformBrowser(this._platformId)) {
             L.map('leafletMap').setView([50.08, 19.93], 13);
        }
        if (isPlatformServer(this._platformId)) {
            // Server only code.
            // https://github.com/angular/universal#universal-gotchas
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Oli*_*ver 5

您可以使用来从DOM中删除一些元素*ngIf。将当前状态写入组件的属性,然后在html文件中进行检查。

component.ts

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

@Component({
  selector: 'mySpecial',
  templateUrl: './mySpecial.component.html'
})
export class MySpecialComponent {
  isBrowser: boolean;

  constructor( @Inject(PLATFORM_ID) platformId: Object) {
    this.isBrowser = isPlatformBrowser(platformId);
  }
}
Run Code Online (Sandbox Code Playgroud)

component.html

<h2>Hello World</h2>
<p>
  <md-select *ngIf="isBrowser" placeholder="Favorite food" name="food">
    <md-option value="Steak">Steak</md-option>
    <md-option value="Pizza">Pizza</md-option>
    <md-option value="Tacos">Tacos</md-option>
  </md-select>
</p>
Run Code Online (Sandbox Code Playgroud)

这将在服务器端创建不包含DOM的DOM,md-select因此不会失败。但是请注意,这可能会导致用户看到的内容发生意外变化,导致该网站首先在没有元素的情况下在浏览器中呈现(这是服务器提供的内容),并且在加载javascript并使angular生效之后突然出现。