yuro
yuro

Reputation: 2209

How to use service in generic class (Angular 7)

I have the following example:

Data model:

export interface SampleList {
    readonly Id: number;
    CompanyName: string;
    Country: string;
}

Component:

export class AppComponent implements OnInit {

  private sampleList = new SampleWrapper<SampleList>();

  constructor() { }

  ngOnInit() {
    this.sampleList.loadData('v_ListOfCompanies');
  }
}

Wrapper class:

export class SampleWrapper<T> {
    public changes: T;
    public original: T;

    private sampleSvc: SampleService;

    constructor() { }

    public loadData(dbView: string) : void {
        this.sampleSvc.getData<T>(dbView)
            .subscribe(
                data => {
                    this.original = data;
                },
                error => {
                    console.log(error);
                }
            );
    }
}

Service:

export class SampleService {

  static readonly apiUrl: string = environment.apiUrl;

  constructor(private http: HttpClient) { }

  getData<T>(dbView: string) : Observable<T> {
    const url = `${SampleService.apiUrl}/${dbView}`;

    return this.http.get<T>(url);
  }
}

The http-Requests fails, because sampleSvc is undefined.

ERROR TypeError: "this.sampleSvc is undefined"

How can I use an ApiService in a wrapper class? Can anyone help me? Or give me some advice about using generic classes in typescript especially Angular 7?

Upvotes: 0

Views: 839

Answers (2)

Stefan
Stefan

Reputation: 1511

You need to provide your service inside of constructor

export class SampleWrapper<T> {
    public changes: T;
    public original: T;

    constructor(private sampleSvc: SampleService) { }

    public loadData(dbView: string) : void {
        this.sampleSvc.getData<T>(dbView)
            .subscribe(
                data => {
                    this.original = data;
                },
                error => {
                    console.log(error);
                }
            );
    }
}

And than you should extends your class instead of create new istance of it

export class AppComponent extends SampleWrapper<SampleList> implements OnInit {

  constructor() { }

  ngOnInit() {
    this.loadData('v_ListOfCompanies');
  }
}

But the best way is to use export class SampleWrapper<T> as service if that component does not have any view.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222552

You are supposed to inject the service using Dependency injection within the constructor

 constructor(private sampleSvc: SampleService) { }

and then use it as,

 this.sampleSvc.getData<T>

Upvotes: 1

Related Questions