簡體   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