本文介绍了如何在启动时将列表(http调用)加载到Angular 5中的应用程序范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在启动时加载数据,例如使用LocationsService的国家/地区.

I'm looking to load data on startup, for example countries in using a 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次).谢谢!

But it doesn't work (raise an error actually). I need this type of lists to be available from startup (load 1 time only). Thanks!

推荐答案

使用APP_INITIALIZER

use APP_INITIALIZER

首先更改您的服务,而不是返回数据,返回Observable

first change your service instead of returning the data, return the 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) =>{});
     })
  }

}

接下来在您的主模块中对其进行初始化

next initialize it in your main module

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 {}

这篇关于如何在启动时将列表(http调用)加载到Angular 5中的应用程序范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 04:52