我正在构建我的api服务。我希望它是普遍的。如何在提供者的定义中定义apiUrl?
这是我的服务:
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());
}
}
我尝试过服务提供商,但似乎deps
必须是类:
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']
};
并在模块中: @NgModule({ 提供者:[ apiServiceProvider ] })
答案 0 :(得分:1)
不要将字符串定义为依赖项,而是查看Non-class dependencies
和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
然后你将使用OpaqueToken
来保存字符串变量:
https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#opaquetoken
https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html