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

1
  • Well, add the http service to the constructor arguments, and construct those obects from an angular component or service where httpSvc is injected. Commented Sep 19, 2017 at 11:16

1 Answer 1

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
],
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the reply, but while instantiating child class with url, i don't want to pass httpService instance, so in this case how it will work?
@SatishLakhani it won't. An object can't use another object without having a reference to that other object.
@SatishLakhani do you mean like calling a static method?
@JBNizet, so is there any other way to achieve the same behaviour i'm asking?
I answered in the comment on your question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.