在Angular中,你可以使用APP_INITIALIZER
来在应用程序加载时显示等待指示器。下面是一个包含代码示例的解决方法:
app-initializer.service.ts
的新服务文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppInitializerService {
constructor(private http: HttpClient) {}
// 定义一个延迟1秒的异步函数
async initializeApp(): Promise {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('App initialized');
}
}
app.module.ts
文件中,将AppInitializerService
添加到providers
数组中,并将APP_INITIALIZER
注入到APP_INITIALIZER
中。修改代码如下:import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AppInitializerService } from './app-initializer.service';
export function initApp(appInitializerService: AppInitializerService) {
return () => appInitializerService.initializeApp();
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
AppInitializerService,
{
provide: APP_INITIALIZER,
useFactory: initApp,
deps: [AppInitializerService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
文件中,添加一个变量来表示是否显示等待指示器,并在模板中使用它。修改代码如下:import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
Loading...
Welcome to my app!
`,
styles: [`
.loader {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
`]
})
export class AppComponent {
showLoader = true;
constructor() {}
}
app.component.ts
文件中,修改AppInitializerService
的initializeApp
方法来切换showLoader
变量的值。修改代码如下:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppInitializerService {
constructor(private http: HttpClient) {}
async initializeApp(): Promise {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('App initialized');
// 在应用程序初始化完成后切换showLoader变量的值
this.showLoader = false;
}
}
styles.css
文件中添加样式来居中显示等待指示器。修改代码如下:.loader {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
现在,当你运行应用程序时,将会在应用程序加载时显示等待指示器,并在应用程序初始化完成后隐藏它。