0

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

Satish Lakhani
  • 445
  • 3
  • 10
  • Well, add the http service to the constructor arguments, and construct those obects from an angular component or service where httpSvc is injected. – JB Nizet Sep 19 '17 at 11:16

1 Answers1

0

You need to inject it like this:

constructor(private http: HttpService)

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

providers:[
 HttpService
],
kodeaben
  • 1,829
  • 3
  • 24
  • 33