angular依赖注入providedIn与懒加载的问题循环依赖

1. providedIn: ‘root’

The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule.

对于一个服务OneService,如果只是在懒加载模块CustomersModule中被使用,providedIn:‘root’ 可以如我们设想的工作:即把OneService和懒加载的模块打包在一起,如此减少代码首次的下载量。看来angular还挺智能的。

2. providedIn:某懒加载模块

2.0 循环依赖问题

懒加载这个模块CustomersModule,CustomersModule里面有个组件CustomerListComponent,CustomerListComponent注入了OneService,

// OneService
@Injectable({
  providedIn: CustomersModule
})

这个时候,我们会看到这样的警告:
在这里插入图片描述

WARNING in Circular dependency detected:
src\app\customers\customer-list\customer-list.component.ts -> src\app\one.service.ts
 -> src\app\customers\customers.module.ts -> src\app\customers\customer-list\customer-list.component.ts

,导航到懒加载模块的时候也会看到这样的错误:
在这里插入图片描述

2.1 解决方法

就是打破循环依赖,创建一个模块OneModule,在其中提供OneService;然后导入到懒加载的模块CustomersModule中。

// CustomersModule 
@NgModule({
  imports: [
    OneModule
  ],
  declarations: [CustomerListComponent]
})
export class CustomersModule { }


// OneModule
import { NgModule } from '@angular/core';

@NgModule({

})
export class OneModule { }


// OneService 
@Injectable({
  providedIn: OneModule
})
export class OneService {
  constructor() {
    console.log(123456789);
  }
}

OneService 可以在OneModule被提供,而CustomersModule导入了OneModule,这样就没有了循环依赖了。

参考文献:
https://angular.io/guide/dependency-injection
https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f
https://upgradetoangular.com/angular-news/providedin-the-angular-6-attribute-you-must-start-using/

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值