How can I pass a string (which will be a url) to a service? Since my 'service' is always going to be an http get request, it makes sense to keep it generic as possible and make the controller pass the url through to it instead of making dozens of separate controllers with different urls in them.
So far my controller looks like this:
this._httpService.getOffers()
.subscribe(
data => { this.offers = <Offer[]>data.offers; },
error => alert(error),
() => console.log("Finished")
);
and in my 'service' it looks like this:
getOffers() {
return this._http.get('json/test.json')
.map(res => res.json())
}
But I want to move "json/test.json" to the controller.
How can I pass a string (which will be a url) to a service? Since my 'service' is always going to be an http get request, it makes sense to keep it generic as possible and make the controller pass the url through to it instead of making dozens of separate controllers with different urls in them.
So far my controller looks like this:
this._httpService.getOffers()
.subscribe(
data => { this.offers = <Offer[]>data.offers; },
error => alert(error),
() => console.log("Finished")
);
and in my 'service' it looks like this:
getOffers() {
return this._http.get('json/test.json')
.map(res => res.json())
}
But I want to move "json/test.json" to the controller.
Share Improve this question asked Jul 5, 2016 at 7:46 Andrew HowardAndrew Howard 3,0926 gold badges40 silver badges71 bronze badges 1-
Just pass a parameter to getOffers function
getOffers(url: string)
– drinovc Commented Jul 5, 2016 at 7:49
2 Answers
Reset to default 9You can do this this way:
getOffers(url:string) { // <----
return this._http.get(url)
.map(res => res.json())
}
and call it like this:
this._httpService.getOffers('json/test.json')
.subscribe(
data => { this.offers = <Offer[]>data.offers; },
error => alert(error),
() => console.log("Finished")
);
this._httpService.getOffers(url:string)
.subscribe(
data => { this.offers = <Offer[]>data.offers; },
error => alert(error),
() => console.log("Finished")
);
getOffers(url:string) {
return this._http.get(url)
.map(res => res.json())
}