【问题标题】:Angular2- Loading config data at the app startupAngular2-在应用启动时加载配置数据
【发布时间】:2017-06-03 04:29:27
【问题描述】:

我正在使用 APP_initializer 在启动时使用 http 从 asp.net web api 加载配置数据。我受到这个 stackoverflow 线程 Angular2 load configuration from backend on startupthis 的启发

我的 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


【解决方案1】:

构造函数(私有_appConfigService:AppConfigService){ 这里的构造函数变量应该是公开的才能访问它。

根据我的经验,如果您打算使用 angular2,最好使用 ng 工具。 Angular-cli

npm install angular-cli -g 阅读这些工具的自述文件。 我不会用 microsoft junk 构建我的前端,即使我已经软弱了 20 多年。

【讨论】:

    【解决方案2】:

    如果在调用ngOnInit() 时它不起作用,但在点击事件中起作用,请尝试使用ngAfterViewInit()。我认为应该可以。 https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

    【讨论】:

    • 感谢您的回复。如果我想在 ngOnInit 上使用一些配置数据怎么办,比如说,我想从 config 获取一个 REST API url,然后我用它来获取数据以填充组件的 html。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多