Angular 4: Inject service having @angular/http as dependency in non-component class

491 Views Asked by At

Hi I'm newbie for Angular 4. I'm having one service named 'httpService' which is having @angular/http as one of dependency, there are others as well, which does error handling.

Now i'm having normal class (other than component) say 'Child.ts' which extends base class 'Base.ts' with constructor which sets some properties on class and uses above mentioned httpService to fetch data from server via rest apis.

My Overall structure looks like below.

Base.ts
============================================================
export class Base {
  public url: string;
  public httpSvc: HttpService;

  constructor(url) {
    this.url = url;
  }

  public getUrl(): string {
    return this.url;
  }

  public query(reqParams: URLSearchParams): Observable<any> {
    return this.httpSvc.get(this.getUrl(), reqParams);
  }
}

And having class which extends base class.

Child.ts
============================================================
export class Child extends Base {
  first_name: string;
  last_name: string;
  email: string;

  constructor(url: string) {
    super(url);
  }

  getCurrentUser(): Observable<User> {
    return this.httpSvc.get(this.url + 'get-user-profile');
  }
}

This way i'm having each model with its own method to fetch data from server.

Now in such situation how can i use httpService as its not initialized yet.

Please suggest me the way or better solution.

Thanks

Satish Lakhani

1

There are 1 best solutions below

6
On

You need to inject it like this:

constructor(private http: HttpService)

remember to provide at a top level, like you app.module:

providers:[
 HttpService
],