piernik
piernik

Reputation: 3657

Passing param to service

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

Answers (1)

Related Questions