Reputation: 3657
I'm building my api service. I want it to be universal. How to define apiUrl in provider's definition?
Here is my service:
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import '/js/admin/rxjs-operators';
import {Observable} from "rxjs";
@Injectable()
export class ApiService {
private apiUrl: string = 'http://www.system.local/api/';
constructor(private http: Http, private apiUrl: string) {
}
get(url: string, params): Observable<Response> {
let requestUrl: string = this.apiUrl + url + this.parseParams(params);
return this.http.get(requestUrl)
.map(response => response.json());
}
post(url: string, params): Observable<any> {
let requestUrl: string = this.apiUrl + url;
return this.http.post(requestUrl, params)
.map(response => response.json());
}
}
I've tried with service provider but seems that deps
has to be class:
import {ApiService} from "./api.service";
import {Http} from "@angular/http";
let apiServiceFactory = (http: Http, apiUrl: string)=> {
return new ApiService(http, apiUrl);
};
export let apiServiceProvider = {
provide: ApiService,
useFactory: apiServiceFactory,
deps: [Http, 'http://www.wp.pl']
};
and in module: @NgModule({ providers: [ apiServiceProvider ] })
Upvotes: 2
Views: 50
Reputation: 96969
Don't defined the string as a dependency and rather have a look at Non-class dependencies
and Value providers
:
https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#non-class-dependencies
https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#value-provider
Then you'll use OpaqueToken
to hold the string variable:
https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#opaquetoken
https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html
Upvotes: 1