我希望在启动时加载数据,例如在使用LocationsService的国家/地区。
我实现了当前服务:
...
@Injectable()
export class LocationsService {
public countries: Country[];
constructor(private http: HttpClient) {
}
public getCountries() {
if (this.countries.length == 0) {
this.http.get<Country[]>(`${this.url}`)
.subscribe(data => { this.countries = data; },
err => console.error(err),
() => console.log(this.countries)
)
};
return this.countries;
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将服务放入引导程序中:
bootstrap: [AppComponent, LocationsService]
Run Code Online (Sandbox Code Playgroud)
但这是行不通的(实际上会引发错误)。我需要这种类型的列表在启动时可用(仅加载1次)。谢谢!
使用APP_初始化器
首先更改您的服务而不是返回数据,而是返回 Observable
@Injectable()
export class LocationsService {
public countries: Country[];
constructor(private http: HttpClient) {
}
public getCountries() {
if (this.countries.length == 0) {
return this.http.get<Country[]>(`${this.url}`);
};
return new Observable( c => {
c.next(this.countries);
c.complete();
});
}
}
Run Code Online (Sandbox Code Playgroud)
创建一个用于设置的服务
@Injectable()
export class SetupLocations {
constructor(private loc: LocationsService ) {
}
public initliaze(): Promise<any> {
return new Promise((resolve, reject) =>{
this.loc.getCountries().subscribe((response) =>{
//Do whatever you want here.
//always call resolve method, because it will freeze your app.
resolve(true);
}, (err) =>{});
})
}
}
Run Code Online (Sandbox Code Playgroud)
接下来在主模块中初始化它
import { NgModule, APP_INITIALIZER } from "@angular/core";
//create a function outside in the class module
export function SetupApp(setup: SetupLocations) {
return () => setup.initliaze();
}
@NgModule({
providers: [
SetupLocations,
{
provide: APP_INITIALIZER,
useFactory: SetupApp,
deps: [SetupLocations],
multi: true
}]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
570 次 |
| 最近记录: |