nguyên cảo: 2.2.0 góc: 4,0Angular4 APP_INITIALIZER sẽ không trì hoãn khởi
Tôi đang cố gắng để đảm bảo rằng một đối tượng ConfigService
được khởi tạo trước khi khởi động ứng dụng thông qua việc sử dụng các APP_INITIALIZER
. Tôi đã tìm thấy nhiều ví dụ về cách làm điều này tuy nhiên KHÔNG ai trong số họ dường như trì hoãn việc khởi tạo ứng dụng. Dưới đây chỉ là một số ví dụ mà tôi đã cố gắng triển khai.
https://github.com/angular/angular/issues/9047 https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9 Angular2 APP_INITIALIZER not consistent
Đây là NgModule
lớp học của tôi
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 {
}
Và đây là lớp 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];
}
}
Và để kiểm tra tất cả mọi thứ tôi đã tiêm ConfigService
i nto AppComponent
với điều này.
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;
}
}
Vâng, đó là những gì nó đã! Cám ơn rất nhiều! – DynaWeb
Đối với những người khác đọc sách này, cũng có một số gần đây (hiện tại) https://juristr.com/blog/2018/01/ng-app-runtime-config/#runtime-configuration – redfox05