【问题标题】:how to load lists (http calls) on startup to application scope in Angular 5?如何在启动时将列表(http调用)加载到Angular 5中的应用程序范围?
【发布时间】:2018-04-06 06:06:19
【问题描述】:

我希望在启动时加载数据,例如使用 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 次)。谢谢!

【问题讨论】:

  • 如果你想加载一次然后在appModule中使用这个服务
  • 将服务添加到:提供者:[ LocationsService ]

标签: angular


【解决方案1】:

使用 APP_INITIALIZER

首先改变你的服务而不是返回数据,返回 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 {}

【讨论】:

  • 我已经尝试了提议的代码,但我得到了 seFactory 的错误:对象文字可能只指定已知属性,并且 'seFactory' 在类型 'Provider' 中不存在。
  • 改成 'useFactory' 抱歉,拼错了
  • 应用无法启动?
  • 已编译且 ng serve 成功,但没有显示任何内容,空白屏幕,您为 app.module.ts 提供的代码中的某些内容已损坏。
  • 对不起,它正在工作!我在服务本身遇到了一个问题,请再问一个问题:我应该在哪里定义应该在应用程序范围内的属性:在 SetupLocations 中执行:公共国家:国家 []; ?并将getter方法添加到同一个?
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多