gpt4 book ai didi

Angular4 APP_INITIALIZER 不会延迟初始化

转载 作者:太空狗 更新时间:2023-10-29 16:51:07 25 4
gpt4 key购买 nike

typescript :2.2.0 Angular :4.0

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

https://github.com/angular/angular/issues/9047 https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9 Angular2 APP_INITIALIZER not consistent

这是我的 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];
}
}

为了测试我用它注入(inject) ConfigServiceAppComponent 中的所有内容。

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

最佳答案

看起来你忘了从工厂返回值:

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

或者同样的代码可以写得更短一些:

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

关于Angular4 APP_INITIALIZER 不会延迟初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43639136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com