简体   繁体   中英

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?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM