【问题标题】:How to use service in generic class (Angular 7)如何在泛型类中使用服务(Angular 7)
【发布时间】:2019-09-24 22:05:26
【问题描述】:

我有以下例子:

数据模型:

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 未定义。

ERROR TypeError: "this.sampleSvc is undefined"

如何在包装类中使用 ApiService?谁能帮我?或者给我一些关于在 typescript 特别是 Angular 7 中使用泛型类的建议?

【问题讨论】:

    标签: angular typescript generics angular7 wrapper


    【解决方案1】:

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

    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&lt;T&gt; 作为服务。

    【讨论】:

    • 初始化 Wrapper 时出现错误 class=> error TS2554: Expected 1 arguments, but got 0.
    • 但我有更多接口.. 查找下拉菜单。我无法在扩展语句中设置所有这些查找。
    • 我已经问过 SampleWrapper 组件是否有视图,如果没有,它肯定应该是一个服务,那么你不必扩展。
    【解决方案2】:

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

     constructor(private sampleSvc: SampleService) { }
    

    然后将其用作,

     this.sampleSvc.getData<T>
    

    【讨论】:

    • 我已经试过了。但是我收到一个错误error TS2554: Expected 1 arguments, but got 0. 我不确定在初始化部分将 SampleService 设置为参数。
    • 这意味着您向服务传递了错误的参数
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2021-09-16
    相关资源
    最近更新 更多