Reputation: 515
I am trying to externalize the url and proerties in angular 6.
Have a service which invokes 3rd party URL to get data.
weather-component.html -> weather.component.ts -> weather.service.ts
In my weather.service.ts,
public getWeather() {
// Here I have hardoded the URL and the api key.
}
I would like to externalize this so as to make it configurable.
Not sure how to move it to a configurable file and read from there.
Upvotes: 0
Views: 1324
Reputation: 1759
Exactly the same manish's answer but when we started the project in Angular 2 , this blog had been quite helpful. Over the upgrades over http gateway has changed massively and it was very useful when angular changed the httpclient in 4 .
https://blog.sstorie.com/adapting-ben-nadels-apigateway-to-pure-typescript
Also if you are looking for a place to put base url etc , I would use the environment ts file in angular-cli https://github.com/angular/angular-cli/wiki/stories-application-environments
Upvotes: 1
Reputation: 4692
I suppose you want to make generic service
you can have a baseHttp.service.ts
and weather.service.ts
will extend the baseHttpservice to make the api calls.
baseHttp.service.ts
@Injectable()
export abstract class BaseHttpService {
private baseUrl: string = Constants.BASEURL;
protected method: string;
protected serviceUrl: string;
protected headers: Headers;
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
call(params: any) {
let url: string = this.setUrl();
let options = new RequestOptions({ headers: this.headers });
options.url = url;
options.method = this.method;
options.body = params;
return this.http.request(url, options).toPromise()
.then((response: any) => this.extractData(response))
.catch((error: any) => this.handleError(error));
}
//complete the other functions
}
weather.service.ts
@Injectable()
export class DashboardService extends BaseHttpService {
constructor(private _http: Http) {
super(_http);
}
getWeatherReport(params:any) {
this.serviceUrl = 'some-url';
this.method = "GET";
return super.call(params);
}
}
so you can inject weather.service.ts and override the values in weather.service.ts and make http calls
so baseHttp.service.ts
acts as a interceptor, so you can intercept all the Http calls there.
Upvotes: 1