टाइपप्रति: 2.2.0 कोणीय: 4.0Angular4 APP_INITIALIZER प्रारंभ में देरी नहीं होगी
मैं यह सुनिश्चित करना है कि एक ConfigService
वस्तु APP_INITIALIZER
के उपयोग के माध्यम आवेदन स्टार्टअप से पहले आरंभ नहीं हो जाता प्रयास कर रहा हूँ। मुझे यह कैसे करना है इसके कई उदाहरण मिल गए हैं, हालांकि उनमें से कोई भी ऐप की शुरुआत में देरी नहीं कर रहा है। यहां कुछ उदाहरण दिए गए हैं जिन्हें मैंने कार्यान्वित करने का प्रयास किया है।
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];
}
}
और मैं ConfigService
इंजेक्शन दिया है सब कुछ परीक्षण करने के लिए है मैं इसके साथ AppComponent
।
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;
}
}
हाँ, यह है कि यह क्या था है! बहुत बहुत धन्यवाद! – DynaWeb
इसे पढ़ने के लिए, यह भी हालिया है (अभी तक) https://juristr.com/blog/2018/01/ng-app-runtime-config/#runtime-configuration – redfox05