![](/img/trans.png)
[英]ReferenceError: window is not defined in angular universal
[英]ReferenceError: window is not defined Angular Universal
我正在使用 Angular 10 並嘗試在我的項目中實現 SSR。
當我運行npm run serve:ssr
我收到以下錯誤
ReferenceError: window is not defined
當我用谷歌搜索時,他們建議添加domino
所以下面是我的 server.ts
....
const scripts = fs.readFileSync('dist/asfc-web/browser/index.html').toString();
const window = domino.createWindow(scripts);
global['window'] = window;
global['document'] = window.document;
....
仍然出現相同的錯誤,請指導我如何解決此問題。
很簡單的解決方法
我在global['window']
之后導入了AppServerModule
並且它有效
global['window'] = window;
global['document'] = window.document;
import { AppServerModule } from '../../projects/asfc-web/src/main.server';
你可以使用 Renderer2 來監聽這個。
import { Renderer2 } from '@angular/core';
constructor(private renderer2: Renderer2) {
...
}
this.renderer2.listen('window', 'load', event => {
this.innerWidth = event.currentTarget.innerWidth;
console.log(this.innerWidth);
});
您可以創建新服務
import {Injectable} from '@angular/core';
function _window(): any {
return window;
}
@Injectable({
providedIn: 'root'
})
export class WindowRef {
get nativeWindow(): any {
return _window();
}
}
在要使用的構造函數中添加:
constructor(
private windowRef: WindowRef
) {
}
並像這樣使用:
this.windowRef.nativeWindow.scrollTo({
top: 0,
behavior: 'smooth'
});
或者您可以檢查平台:
constructor(
@Inject(PLATFORM_ID) private platformId: any,
private windowRef: WindowRef
) {
}
if (isPlatformBrowser(this.platformId)) {
this.windowRef.nativeWindow.scrollTo({
top: 0,
behavior: 'smooth'
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.