【问题标题】:ReferenceError: window is not defined with Angular UniversalReferenceError:没有使用 Angular Universal 定义窗口
【发布时间】:2019-03-29 18:31:09
【问题描述】:

Angular 7 中出现此问题。我已将应用程序从 Angular 6 升级到 Angular 7

收到此错误:

 var user_id = window.localStorage.getItem('user_id');
              ^

ReferenceError: window is not defined
    at Object../src/app/global_variable.ts (D:\Project\public\dist\server.js:208477:15)
    at __webpack_require__ (D:\Project\public\dist\server.js:169701:30)
    at Object../src/app/services/auth.service.ts

【问题讨论】:

  • @Kingslayer 省略不起作用,因为现在 localStorage 没有定义

标签: angular universal


【解决方案1】:

通用工具包在服务器端呈现代码,并且窗口对象仅在浏览器中可用,这就是您收到此错误的原因。

您可以使用isPlatformBrowser 模块添加条件以仅在浏览器上执行客户端代码。

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

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html"
})
export class AppComponent implements OnInit {

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

   ngOnInit() {

     // Client only code.
     if (isPlatformBrowser(this.platformId)) {
        // write your client side code here
     }

   }
 }

【讨论】:

    【解决方案2】:

    "window" 是 Javascript 中的全局对象,所以如果没有冲突的机会,你可以省略它。 试试这个,

    var user_id = localStorage.getItem('user_id');
    

    【讨论】:

    • 通过使用我上面给出的解决方案
    • 省略不起作用,因为现在 localStorage 没有定义@Kingslayer
    【解决方案3】:

    当您在应用程序中添加 Angular Universal 时 windowdocumentnavigator 和其他浏览器类型 - 在服务器上不存在 - 所以使用它们或任何使用它们的库(例如 jQuery)不管用。

    如果您需要使用它们,请考虑将它们限制为仅限您的客户使用,并根据情况进行包装。您可以使用使用PLATFORM_ID令牌注入的Object来检查当前平台是浏览器还是服务器。

    在我的项目中,我在组件 ts file 中有以下代码,它正在工作

    import { WINDOW } from '@ng-toolkit/universal';
    import { Component, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    
    @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
     })
    
      export class AppComponent {
      title = 'app';
    
      constructor(@Inject(WINDOW) public window: Window,
        @Inject(PLATFORM_ID) private platformId: Object) {
      }
    
      onActivate(event) {
        if (isPlatformBrowser(this.platformId)) {
          this.window.scroll(0, 0);  // window object used which is Instance of Window 
    
        }
      }
    
     }
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2020-05-28
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2020-09-16
      相关资源
      最近更新 更多