首页 > 解决方案 > Angular服务在构造函数中调用子方法

问题描述

有没有办法从抽象服务调用子类方法?当我这样做时,该if语句不会执行,因为onInit不存在。我不确定为什么它不存在。也许有一种“角度”的方式来做到这一点,而不是在初始化时触发它。或者,也许我只需要在组件中手动调用 onInit。基本上我正在做的是尝试从服务器获取初始应用程序数据。

@Injectable({providedIn:'root'})
export class RootService {
  public constructor(httpClient: HttpClient) {
    if(typeof this.onInit === 'function') {
      this.onInit()
    }
  }
}
@Injectable({providedIn:'root'})
export class MyService extends RootService {
  public onInit() {
    // Do stuff
  }
}
@Component()
export MyComponent {
  public constructor(myService: MyService) {}
}

标签: javascriptangulartypescript

解决方案


服务没有生命周期事件。但是,组件具有生命周期挂钩,例如:

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ...

因此,您可以在组件初始化时加载数据。如果是,那么只需使用ngOnInit

import { Component, OnInit } from '@angular/core';

@Component()
export MyComponent  implements OnInit {
    yourData;

    public constructor(myService: MyService) {}

    ngOnInit(){
        myService.loadData()
            .subscribe(s=> yourData = s);
    }
}

根据 Angular 文档:

OnInit 是一个生命周期钩子,在 Angular 初始化指令的所有数据绑定属性后调用。


推荐阅读