简体   繁体   English

如何在通用类中使用服务(Angular 7)

[英]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. http-Requests失败,因为未定义sampleSvc

ERROR TypeError: "this.sampleSvc is undefined" 错误TypeError:“ this.sampleSvc未定义”

How can I use an ApiService in a wrapper class? 如何在包装类中使用ApiService? Can anyone help me? 谁能帮我? Or give me some advice about using generic classes in typescript especially Angular 7? 或者给我一些有关在打字稿中使用通用类的建议,尤其是Angular 7?

You are supposed to inject the service using Dependency injection within the constructor 您应该在构造函数中使用Dependency injection来注入服务

 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. 但是最好的方法是,如果该组件没有任何视图,则使用export class SampleWrapper<T>作为服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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