2016-09-22 127 views
2

我正在構建我的api服務。我希望它是普遍的。如何在提供者的定義中定義apiUrl?將param傳遞給服務

這裏是我的服務:

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

可能重複的[Angular 2「沒有字符串提供程序!」](http://stackoverflow.com/questions/39628768/angular-2-no-provider-for-string) –

回答

1
+0

所以所有的配置值應該從服務並注入該服務? – piernik

+0

是的,看看這個examaple:https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html – martin

+0

好的謝謝 - 必須閱讀越來越多:) – piernik