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

时间:2019-05-07 09:14:33

标签: angular typescript generics angular7 wrapper

我有以下示例:

数据模型:

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

组件:

export class AppComponent implements OnInit {

  private sampleList = new SampleWrapper<SampleList>();

  constructor() { }

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

包装类:

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);
                }
            );
    }
}

服务:

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);
  }
}

http请求失败,因为sampleSvc未定义。

  

错误TypeError:“ this.sampleSvc未定义”

如何在包装类中使用ApiService?谁能帮我?或给我一些有关在打字稿中使用泛型类(尤其是Angular 7)的建议?

2 个答案:

答案 0 :(得分:1)

您应该在构造函数中使用Dependency injection注入服务

 constructor(private sampleSvc: SampleService) { }

然后将其用作

 this.sampleSvc.getData<T>

答案 1 :(得分:0)

您需要在构造函数内部提供服务

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);
                }
            );
    }
}

然后您应该扩展您的类,而不是为其创建新的距离

export class AppComponent extends SampleWrapper<SampleList> implements OnInit {

  constructor() { }

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

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