Angular4 APP_INITIALIZER 不会延迟初始化 [英] Angular4 APP_INITIALIZER won't delay initialization

查看:18
本文介绍了Angular4 APP_INITIALIZER 不会延迟初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿:2.2.0角度:4.0

我试图通过使用 APP_INITIALIZER 确保在应用程序启动之前初始化 ConfigService 对象.我找到了很多关于如何执行此操作的示例,但是它们似乎都没有延迟应用程序的初始化.以下是我尝试实施的一些示例.

I am attempting to ensure that a ConfigService object is initialized before application startup through the use of APP_INITIALIZER. I've found many examples of how to do this however NONE of them seem to be delaying the initialization of the app. Here are just a handful of examples I've attempted to implement.

https://github.com/angular/angular/issues/9047https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306dbAngular2 APP_INITIALIZER 不一致

这是我的 NgModule

export function init(config: ConfigService) {
  return () => {
    config.load();
  };
}


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [
    {
      'provide': APP_INITIALIZER,
      'useFactory': init,
      'deps': [ConfigService],
      'multi': true
    },
    ConfigService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

这里是 ConfigService

@Injectable()
export class ConfigService {
  private config: ApplicationConfiguration;

  get apiRoot() {
    return this.getProperty('apiRoot'); // <--- THIS GETS CALLED FIRST
  }

  constructor(private http: Http) {
  }

  load(): Promise<any> {
      console.log('get user called');
      const promise = this.http.get('./../../assets/config.json').map((res) => res.json()).toPromise();
      promise.then(config => {
        this.config = config;     // <--- THIS RESOLVES AFTER
        console.log(this.config);
      });
    return promise;
  }

  private getProperty(property: string): any {
    //noinspection TsLint
    if (!this.config) {
      throw new Error(`Attempted to access configuration property before configuration data was loaded, please double check that 'APP_INITIALIZER is properly implemented.`);
    }

    if (!this.config[property]) {
      throw new Error(`Required property ${property} was not defined within the configuration object. Please double check the 
      assets/config.json file`);
    }

    return this.config[property];
  }
}

为了测试我将 ConfigService 注入到 AppComponent 中的所有内容.

And to test everything I've injected ConfigService into AppComponent with this.

import { Component } from '@angular/core';
import {ConfigService} from './services/config.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app works!';
  fullImagePath = '/src/image/avatar.jpeg';


  constructor(private config: ConfigService) {
    config.apiRoot;
  }
}

推荐答案

你好像忘记从工厂返回值了:

Looks like you forgot to return value from factory:

export function init(config: ConfigService) {
  return () => {
    return config.load(); // add return
  };
}

或者同样的代码可以稍微写一下:

or the same code can be written a bit shortly:

export function init(config: ConfigService) {
   return () => config.load();
}

这篇关于Angular4 APP_INITIALIZER 不会延迟初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆