2

I am new to angular. I have a json file where I can configure the url that I need to use in my app.

app/config/development.json

{
   "apiUrl": "http://staging.domain.com:9000/",
   "debugging": true
}

And below is my code in config.service.ts:

export class ConfigService {
    private apiURL:any;
    constructor (private http: Http) {}

   getApiURL(){
       this.http.get("app/config/development.json").map(res:Response=>res.json())
      .subscribe(data=>{
         this.apiURL = data;

       })

        console.log(this.apiURL);//this returns undefined
   }

}

I want to make this.apiURL to contain the response of the http.get. And when I create another method, the value of this.apiURL is still the same from the method getAPIURL().

someMethod()
{
   console.log(this.apiURL)//this must contain the response from http.get
}
asHkER
  • 415
  • 4
  • 16
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – eko Jan 26 '17 at 06:35
  • Hi @echonax. Thanks for your comment but is not the answer that I am looking for. I am developing in angular2 and it's different from jQuery ajax call that is mentioned on the link you have posted. – asHkER Jan 26 '17 at 06:49
  • Better practice is service should always return observable/promise & You need to fulfill/resolve that in your component class. Please refer https://scotch.io/tutorials/angular-2-http-requests-with-observables – Parth Ghiya Jan 26 '17 at 06:51
  • Hi @Parth can you give me an example answer of using observable and promise. – asHkER Jan 26 '17 at 06:53

1 Answers1

1

You can do something like this. In your service file.

//whatever model u defined
       getApiURL():Observable<Object[]>{     
      return this.http.get(this.whateverURL)
                .map(res:Response=>res.json())
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

In your component file

  yourData:Object[];
  //whatever Model u defined.
  //assuming yourService is your service instance which u did in constructor.
  this.yourService.getApiURL()
        .subscribe(
            yourData=>{
              this.yourData=yourData;               
            },err=>{
              console.log(err);
              alert("Something went wrong");
            }
        )
  }
Parth Ghiya
  • 6,929
  • 2
  • 30
  • 37