import { APP_INITIALIZER, NgModule } from '@angular/core';
import { MyService } from './services/my.service';
export function initializeApp( myService: MyService) {
return () => {
return myService.initialize();
};
}
@NgModule({
providers: [
MyService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
multi: true,
deps: [MyService]
}
]
})
export class AppModule {}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MyService {
private myData: any[];
constructor(private http: HttpClient) {}
initialize(): Promise {
return new Promise((resolve, reject) => {
this.http.get('/api/data').subscribe(
(data) => {
this.myData = data;
resolve(true);
},
(error) => {
console.log('Error fetching data', error);
reject(error);
}
);
});
}
getData(): any[] {
return this.myData;
}
}
import { Component, OnInit } from '@angular/core';
import { MyService } from './services/my.service';
@Component({
selector: 'my-component',
template: '{{data}}'
})
export class MyComponent implements OnInit {
myData: any[];
constructor(private myService: MyService) {}
ngOnInit() {
this.myData = this.myService.getData();
}
}
这样,我们在应用程序启动时