繁体   English   中英

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

[英]How to use service in generic class (Angular 7)

我有以下示例:

资料模型:

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-Requests失败,因为未定义sampleSvc

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

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

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

 constructor(private sampleSvc: SampleService) { }

然后将其用作

 this.sampleSvc.getData<T>

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

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>作为服务。

暂无
暂无

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

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