2016-03-14 229 views
1

我正在製作一個新的angular2應用程序,它將在我們所有服務器上的所有應用程序上點擊一個端點以獲取內部版本號,然後它將顯示在網格中,以便我們看到服務器具有哪些內部編號。Angular2從配置文件中讀取

當我使用Angular1構建類似的應用程序時,我能夠使用gulp-ng-config來讀取JSON文件並使用JSON中的值輸出角度模塊。我期待在Angular2中做類似的事情,但我不知道如何做到這一點。有任何想法嗎?

回答

5

這樣,你去閱讀.json文件中Angular2
注意:這樣您可以讀取.json文件。此演示顯示.json文件示例。

working demo =>點擊friends tab

http.get('friends.json (=filepath)') 
    .map(res => res.json()) 
    .subscribe((data) => { this.result=data; }, 
          err=>console.log(err), 
          ()=>console.log('done') 
       ); 
+0

感謝一如既往micronyks! –

+0

不客氣@Alex Kibler !!! – micronyks

-2

正常$ http獲取調用配置文件應該滿足您的要求。

$http.get('path-to-configuration-file') 
    .success(function (confData) { 
    // Use your conf data however you like 
    }) 
    .error(function() { 
     // File not found 
    }); 

我希望這個作品

+0

雖然噸帽子實際上是有道理的,你不是說'Http'?我不認爲$ http是在angular2 –

+0

@AlexKibler:感謝您的更正。 Http就是我的意思。對angular2不太熟悉,但作爲一個想法http應該爲這個問題工作 – ganeshwani

4

的最佳方式來讀取配置文件中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 { 
}