简体   繁体   中英

Angular 2 - Pass parameters to service

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.

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())
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM