最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 - Pass parameters to service - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 9

You 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())
        }
发布评论

评论列表(0)

  1. 暂无评论