【发布时间】:2017-06-03 04:29:27
【问题描述】:
我正在使用 APP_initializer 在启动时使用 http 从 asp.net web api 加载配置数据。我受到这个 stackoverflow 线程 Angular2 load configuration from backend on startup 和 this 的启发
我的 app.module.ts
providers: [
HttpClient,
{
provide: APP_INITIALIZER,
useFactory: (appConfigSvc:AppConfigService) => () => {
appConfigSvc.load();
},
deps: [AppConfigService],
multi: true
}, AppConfigService
appConfig.Service.ts
@Injectable()
export class AppConfigService {
private serviceApiUrl = "api/AppConfigApi/";
public applicationConfig: Appconfigmodel.IAppConfigModel;
constructor(private _http: Http) {
}
getApiConfig(): Appconfigmodel.IAppConfigModel {
return this.applicationConfig;
}
load() { this.getApplicationConfig(); }
getApplicationConfig(): Observable<Appconfigmodel.IAppConfigModel> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers
});
//pulling config data from web.config of a ASP.Net Web API2
return this._http.get(this.serviceApiUrl + 'GetApplicationConfig', options)
.map((response: Response) => <Appconfigmodel.IAppConfigModel>response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
然后像这样在任何组件中使用它:
export class FirstComponent {
constructor(private _appConfigService: AppConfigService) {
}
ngOnInit() {
this.applicationConfig= this._appConfigService.getApiConfig(); // The config dat is getting as undefined
}
//button click
clickButton()
{
this.applicationConfig= this._appConfigService.getApiConfig(); // The config data is populated here
}
}
问题是,我无法访问任何组件的 ngOninit 中的配置数据。但它可以在按钮单击事件处理程序或类似方法中访问,这些方法通常在应用程序启动后一段时间被调用。
感谢任何帮助。 谢谢。
【问题讨论】:
-
请提供任何帮助
标签: angular typescript