我正在尝试在我的angular7应用程序中通过'provideIn'属性将服务注册到特定模块。
test.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestComponent} from './test.component'
@NgModule({
declarations: [TestComponent],
imports: [
CommonModule
],
exports: [TestComponent]
})
export class TestModule { }
test.component
import { Component, OnInit } from '@angular/core';
import { TestServiceService } from '../test-service.service';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
constructor(public service: TestServiceService) { }
ngOnInit() {
}
}
test-service.ts
import { Injectable } from '@angular/core';
import { TestModule } from './test/test.module';
@Injectable({
providedIn: TestModule
})
export class TestServiceService {
val = 3;
constructor() { }
getDetails() {
return this.val;
}
}
当我运行我的应用程序时,它显示以下错误
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[TestComponent -> TestServiceService]:
StaticInjectorError(Platform: core)[TestComponent -> TestServiceService]:
NullInjectorError: No provider for TestServiceService!
当我将ProvideIn属性值更改为'root'时,一切正常。如何在angular7中通过'provideIn'属性将服务注册到特定模块?
答案 0 :(得分:1)
将test.component更改为此:
import { Component, OnInit } from '@angular/core';
import { TestServiceService } from '../test-service.service';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
providers : [TestServiceService]
})
export class TestComponent implements OnInit {
constructor(public service: TestServiceService) { }
ngOnInit() {
}
}
,如果您想在模块中拥有单个服务实例,请将test.module.ts更改为:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestComponent} from './test.component'
@NgModule({
declarations: [TestComponent],
imports: [
CommonModule
],
providers :[TestServiceService ],
exports: [TestComponent]
})
export class TestModule { }
做其中之一
答案 1 :(得分:0)
TestService必须依赖于TestModule才能使用provideIn向模块提供服务。这将创建循环依赖关系,因为TestModule必须依赖于依赖TestService的TestComponent。在模块中定义提供程序,以使模块取决于组件和服务。
@NgModule({
declarations: [TestComponent],
imports: [
CommonModule
],
providers: [
TestService
],
exports: [TestComponent]
})
export class TestModule { }
将服务定义为Injectable,并将providerIn设置为null。
@Injectable({
providedIn: null
})
export class TestServiceService {
val = 3;
constructor() { }
getDetails() {
return this.val;
}
}