[英]Angular2 Read from Configuration File
我正在制作一個新的angular2應用程序,它將在所有服務器上的所有應用程序上命中一個端點,以獲取內部版本號,然后將其顯示在網格中,以便我們可以查看哪些服務器具有哪些內部版本號。
當我使用Angular1構建類似的應用程序時,我能夠使用gulp -ng-config讀取JSON文件並輸出帶有JSON值的angular模塊。 我正在尋找在Angular2中做類似的事情,但我不知道如何實現這一點。 有任何想法嗎?
這樣,你去閱讀.json
文件中Angular2
。
注意 :這樣您可以讀取.json
文件。 此演示顯示了.json
文件示例。
工作演示 =>單擊“ friends tab
http.get('friends.json (=filepath)')
.map(res => res.json())
.subscribe((data) => { this.result=data; },
err=>console.log(err),
()=>console.log('done')
);
在Angular2版本2.1.0.0中讀取配置文件的最佳方法是,您的服務如下所示
@Injectable()
export class ConfigService {
private Server:string = "";
private AppKey = "";
constructor(private _http:Http) {
}
public load() {
return new Promise((resolve, reject) => {
this._http.get('config.json') // path of your config.json file
.map(res => res.json())
.subscribe(
(data:any) => {
this.Server = data.server;
this.AppKey = data.appkey;
resolve(true);
},
err=>console.log(err)
);
});
}
public getServer(){
return this.Server;
}
public getAppKey(){
return this.AppKey;
}
}
您必須像這樣加載此配置app.module.ts
@NgModule({
declarations: [
..
],
imports: [
...
],
providers: [ConfigService,
{
provide: APP_INITIALIZER,
useFactory: (config:ConfigService) => () => config.load(),
deps: [ConfigService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
通常,對配置文件的$ http get調用即可滿足您的要求。
$http.get('path-to-configuration-file')
.success(function (confData) {
// Use your conf data however you like
})
.error(function () {
// File not found
});
我希望這行得通
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.