6

我正在尝试在 Angular Universal 中使用 isBrowser 函数,但是在构建时我不断收到相同的错误。我确实安装了 angular-universal 的 npm 包

npm i angular2-universal --save

'ng build -prod -aot'

 ERROR in Illegal state: symbol without members expected, but got {"filePath":"C:/dir/universal/website/node_modules/@angular/platform-browser/platform-browser.d.ts","name":"__platform_browser_private__","members":["BROWSER_SANITIZATION_PROVIDERS"]}.

    ERROR in ./src/main.ts
    Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'C:/dir/universal/website\src'
     @ ./src/main.ts 4:0-74
     @ multi ./src/main.ts

这是我的 app.module.ts:

//modules
import { HomeModule } from './home/home.module';
import { IntakeFormulierModule } from './intake-formulier/intake-formulier.module';
import { BrowserModule } from '@angular/platform-browser';
import { UniversalModule } from 'angular2-universal/browser';

import { NgModule } from '@angular/core';

//routing
import { routing } from "./app.routing";

//pages
import { AppComponent } from './app.component';

//isbrowser
import { isBrowser } from 'angular2-universal';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule.withServerTransition({
        appId: 'website-u - (starter)'
    }),
    HomeModule,
    IntakeFormulierModule,
    routing,
  ],
  providers: [
  { provide: 'isBrowser', useValue: isBrowser }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是我的 app/home/landing/landing.ts

import { Component, Inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({
...
})
export class LandingComponent {

  constructor(//public updateTop: TopImageUpdateService, 
  public router: Router,
   @Inject('isBrowser') public isBrowser: boolean) {}

  navigateToResults(name) {
    if (this.isBrowser) {  
    let scrollToTop = window.setInterval(() => {
      let pos = window.pageYOffset;
      if (pos > 0) {
        window.scrollTo(0, pos - 10); // how far to scroll on each step
      } else {
        window.clearInterval(scrollToTop);
        this.router.navigate(['home/page', name]);
      }
    }, 9)
  }
}

}
4

1 回答 1

16

看起来他们在角度通用示例中使用 isPlatformBrowser() 而不是 isBrowser() 。 https://github.com/angular/universal#universal-gotchas

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements {

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

  ngOnInit(){
    if (isPlatformBrowser(this.platformId)) {
     //Client only code.
    } else {
     //Server only code.
    }
  }
}
于 2017-04-25T19:45:32.070 回答