1

I'm making a new angular2 application which will hit an endpoint on all of our applications on all of our servers to get build numbers, and then it will display them in a grid so we can see which servers have which build numbers.

When I built a similar application using Angular1, I was able to use gulp-ng-config to read a JSON file and output an angular module with the values from the JSON. I'm looking to do something similar in Angular2, but I have no idea how to accomplish this. Any ideas?

Alex Kibler
  • 4,674
  • 9
  • 44
  • 74

3 Answers3

5

This way you go read .json file in Angular2.
Note: This way you can read .json file. This demo shows .json file example.

working demo => click friends tab

http.get('friends.json (=filepath)')
    .map(res => res.json())
    .subscribe((data) => {  this.result=data; },
                            err=>console.log(err),
                            ()=>console.log('done')
               );
micronyks
  • 54,797
  • 15
  • 112
  • 146
4

The best way to read configuration file in Angular2 release version 2.1.0.0 is like, your service would be something like below

    @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;
        }
  }

you have to load this configuration app.module.ts like

@NgModule({
  declarations: [
  ..
  ],
  imports: [
    ...
    ],
  providers: [ConfigService,
      {
      provide: APP_INITIALIZER,
      useFactory: (config:ConfigService) => () => config.load(),
      deps: [ConfigService],
      multi: true
    }


  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
Md Ayub Ali Sarker
  • 10,795
  • 4
  • 24
  • 19
-2

Normal $http get call to the configuration file should suffice your requirement.

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

I hope this works

ganeshwani
  • 19
  • 4
  • While that actually makes sense, don't you just mean `Http`? I didn't think $http was in angular2 – Alex Kibler Mar 14 '16 at 15:37
  • @AlexKibler: thanks for the correction. Http is what I meant. Not much familiar with angular2, but as an idea http should work for this problem – ganeshwani Mar 14 '16 at 15:43