我希望在启动时加载数据,例如使用 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;
}
}
我尝试将服务放入引导程序中:
bootstrap: [AppComponent, LocationsService]
但它不起作用(实际上引发错误)。我需要这种类型的列表从启动时就可用(仅加载 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();
});
}
}
创建一个用于设置的服务
@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) =>{});
})
}
}
接下来在主模块中初始化它
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 {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)