我是angular6的新手,并尝试在@Injectable()装饰器中的ProvideIn属性的帮助下进行依赖项注入。
stockservice.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HelloModule } from './hello/hello.module';
@Injectable({
providedIn: HelloModule
})
export class StockserviceService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('http://localhost:4000/result');
}
}
hellocomponent
import { Component, OnInit } from '@angular/core';
import { StockserviceService } from '../stockservice.service';
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.scss']
})
export class HelloComponent implements OnInit {
constructor(private service: StockserviceService) { }
ngOnInit() {
}
}
hello.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [
CommonModule
],
declarations: [HelloComponent],
exports: [HelloComponent]
})
export class HelloModule { }
在上面的代码中,我将服务注册为HelloModule的提供程序。我知道我们可以通过将'provideIn'属性值替换为'root'将服务注册为单例,但是我需要将服务注册为仅限HelloModule的提供程序。当我在home组件中导入服务时,它显示以下警告。
WARNING in Circular dependency detected:
src/app/hello/hello.component.ts -> src/app/stockservice.service.ts -> src/app/hello/hello.module.ts -> src/app/hello/hello.component.ts
WARNING in Circular dependency detected:
src/app/hello/hello.module.ts -> src/app/hello/hello.component.ts -> src/app/stockservice.service.ts -> src/app/hello/hello.module.ts
WARNING in Circular dependency detected:
src/app/stockservice.service.ts -> src/app/hello/hello.module.ts -> src/app/hello/hello.component.ts -> src/app/stockservice.service.ts
我该如何解决此问题,并借助“ provideIn”属性仅为HelloModule注册服务?