猿问

角度服务调用构造函数中的子方法

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


@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) {}

}


沧海一幻觉
浏览 96回答 2
2回答

守候你守候我

服务没有生命周期事件。但是,组件具有生命周期挂钩,例如:恩贡改变()ngOnInit()ngDoCheck()...因此,您可以在初始化组件时加import { Component, OnInit } from '@angular/core';@Component()export MyComponent  implements OnInit {    yourData;    public constructor(myService: MyService) {}    ngOnInit(){        myService.loadData()            .subscribe(s=> yourData = s);    }}载数据。如果是,则只需使用 :ngOnInit根据角度文档:OnInit 是一个生命周期挂钩,在 Angular 初始化指令的所有数据绑定属性后调用。

扬帆大鱼

如果将服务添加到组件的提供程序,则该服务将位于组件范围内,然后也可以在服务中调用 onInit。但这样做的缺点是,您无法再在组件之间共享相同的服务实例。如果您的服务仅提供一个组件,则此方法有效。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答