在Angular 7中出现此问题。我已将应用程序从角度6升级到角度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
“window”是Javascript中的全局对象,因此如果没有冲突的机会,您可以省略它。试试这个,
var user_id = localStorage.getItem('user_id');
通用工具包在服务器端呈现代码,窗口对象仅在浏览器中可用,这就是您收到此错误的原因。
您可以使用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
}
}
}
当您在应用程序window
,document
,navigator
和其他浏览器类型中添加角度通用时 - 在服务器上不存在 - 因此使用它们或任何使用它们的库(例如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
}
}
}