要在Angular Universal中使用window API,并在合适的生命周期钩子中执行相关代码,可以按照以下步骤进行操作:
AfterViewInit
和Inject
:import { AfterViewInit, Component, Inject } from '@angular/core';
AfterViewInit
接口:export class AppComponent implements AfterViewInit {
// ...
}
window
对象:constructor(@Inject(WINDOW) private window: Window) {}
ngAfterViewInit
生命周期钩子中执行window API相关的代码:ngAfterViewInit() {
if (this.window) {
// 在这里执行window API相关的代码
}
}
将上述代码整合到一个完整的示例中,如下所示:
import { AfterViewInit, Component, Inject } from '@angular/core';
import { WINDOW } from '@ng-web-apis/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
constructor(@Inject(WINDOW) private window: Window) {}
ngAfterViewInit() {
if (this.window) {
// 在这里执行window API相关的代码
}
}
}
请注意,为了使用WINDOW
注入令牌,你需要首先安装@ng-web-apis/common
包:
npm install @ng-web-apis/common
然后,在AppModule中注册该注入令牌:
import { NgxWebApisModule, WINDOW } from '@ng-web-apis/common';
@NgModule({
imports: [
// ...
NgxWebApisModule
],
providers: [
// ...
{ provide: WINDOW, useValue: window }
],
bootstrap: [AppComponent]
})
export class AppModule { }
这样,当Angular Universal应用在浏览器中运行时,window API相关的代码将在ngAfterViewInit钩子中执行。而当应用在服务器上运行时,由于window对象不可用,相关代码将被跳过。