代码之家  ›  专栏  ›  技术社区  ›  Ronaldo Lanhellas

使用abstract在typescript中创建基组件

  •  3
  • Ronaldo Lanhellas  · 技术社区  · 6 年前

    我正在尝试使用列表页中使用的一些默认方法创建基本组件,因此这是我的TS文件:

    export abstract class BaselistComponent<T> implements OnInit {
      source: LocalDataSource = new LocalDataSource();
    
      constructor(private service: BasecrudService<T>,
                  private notification: NotificationService) {
      }
    
       ngOnInit(): void {
        this.service.findRecords().subscribe((data: T[]) => {
          this.source.load(data);
        });
      }
    }
    

    现在我有了使用这个基础的组件:

    @Component({
      selector: 'ngx-unidade',
      templateUrl: './unidade.component.html',
      styleUrls: ['./unidade.component.scss'],
    })
    export class UnidadeComponent extends BaselistComponent<Unidade> {
    
       constructor(service: UnidadeService, notification: NotificationService) {
        super(service, notification);
      }
    }
    

    当我尝试执行我的应用程序时,我 Cannot read property 'findRecords' of undefined 我知道这个错误是因为 this.service 是未定义的,但我不知道为什么,我已经声明了。

    这是我的服务基地:

    export abstract class BasecrudService<T> {
    
      constructor(private http: HttpClient, private adapter: Adapter<T>) {
      }
    
      abstract getPrefixURL(): string;
    
      findRecords(): Observable<T[]> {
        return this.http.get(`${environment.apiUrl}/${this.getPrefixURL()}/pagina/0`).pipe(
          map((data: any) => data.registros.map(item => this.adapter.adapt(item))),
        );
      }
    }
    

    服务实现:

    @Injectable({
      providedIn: 'root',
    })
    export class UnidadeService extends BasecrudService<Unidade> {
    
      constructor(http: HttpClient, adapter: Adapter<Unidade>) {
        super(http, adapter);
      }
    
      getPrefixURL(): string {
        return 'unidades';
      }
    
    }
    

    编辑1

    这是我的 console.log(this) 请注意我的 service 未定义

    enter image description here

    编辑2 这是我的项目完整来源: https://github.com/rlanhellas/safepark-front

    1 回复  |  直到 6 年前
        1
  •  1
  •   yurzui    6 年前

    产生错误的原因是在角度DI中使用了接口。

    工发组织.service.ts

    export class UnidadeService extends BasecrudService<Unidade> {
    
      constructor(http: HttpClient, adapter: Adapter<Unidade>) {
                                             ^^^^^^^
        super(http, adapter);
      }
    }
    

    这会导致DI错误,所以您不会 UnidadeService 初始化