当用另一个服务扩展服务时,Angular 中的服务会被实例化两次

问题描述 投票:0回答:1

在我的 Angular 项目中,我设置了多个服务。一项服务具有一些我想限制访问的功能,以便只能从一项特定的其他服务中使用它。

为了实现这一点,我想在调用服务中扩展服务,并使用 protected 访问修饰符来限制访问。但是,在实现此操作后,当我启动应用程序时,我看到父服务有两个实例。如何强制父服务仅实例化一次(作为单例)?或者,我应该如何以不同的方式解决这个问题,以确保只能从调用服务访问一个服务中的功能?

父服务伪代码:

@Injectable({
  providedIn: 'root'
})
export class ParentService {

  constructor() {
    // below is logged twice!
    console.log('new instance of ParentService created');
  }

  public someFunction() {}

  protected functionIWantToLimitAccessTo() {}

}

子服务伪代码:

import { ParentService} from './parent.service';

@Injectable({
  providedIn: 'root'
})
export class ChildService extends ParentService {

  constructor() {
    super();  // <- this super() call is needed for class extension
  }

  public publicFunction() {
    super.functionIWantToLimitAccessTo();
  }

}

我本以为此设置中只有一个 ParentService 实例。

angular inheritance service singleton extend
1个回答
0
投票

为什么不使用依赖注入的力量?并将所需的服务注入到您的构造函数中

 import { ParentService} from './parent.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ChildService  {
    
    
      constructor(private parentService: ParentService) {
      }
    
    
      public publicFunction() {
        this.parentService.unctionIWantToLimitAccessTo();
      }
    
    }
© www.soinside.com 2019 - 2024. All rights reserved.