[英]ReferenceError: window is not defined Angular Universal
I'm using Angular 10 and trying to implement SSR in my project.我正在使用 Angular 10 并尝试在我的项目中实现 SSR。
When I run the npm run serve:ssr
I'm getting the below error当我运行npm run serve:ssr
我收到以下错误
ReferenceError: window is not defined
When I googled, they suggested to add domino
当我用谷歌搜索时,他们建议添加domino
So below is my server.ts所以下面是我的 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;
....
still getting the same error, Please guide me how to resolve this issue.仍然出现相同的错误,请指导我如何解决此问题。
It's simple fix,很简单的解决方法
I've imported the AppServerModule
after the global['window']
and it worked我在global['window']
之后导入了AppServerModule
并且它有效
global['window'] = window;
global['document'] = window.document;
import { AppServerModule } from '../../projects/asfc-web/src/main.server';
you can use Renderer2 listen for this.你可以使用 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);
});
You can create new service您可以创建新服务
import {Injectable} from '@angular/core';
function _window(): any {
return window;
}
@Injectable({
providedIn: 'root'
})
export class WindowRef {
get nativeWindow(): any {
return _window();
}
}
add in constructor where you want to use:在要使用的构造函数中添加:
constructor(
private windowRef: WindowRef
) {
}
and use like this:并像这样使用:
this.windowRef.nativeWindow.scrollTo({
top: 0,
behavior: 'smooth'
});
or you can check platform:或者您可以检查平台:
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.