在下面的代码示例中,app.module设置用于Angular依赖注入的提供程序 . Angular因此具有对DataService类的引用 .
// app.module.ts
import { DataService } from './services/dataService';
import { LocationsComponent } from './components/locations.component';
@NgModule({
declarations: [
AppComponent,
LocationsComponent,
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [
DataService
],
bootstrap: [AppComponent]
})
export class AppModule { }
我的理解是在locations.component中Angular将执行DI以在构造函数中创建DataService类的新实例 . 我不明白为什么组件中需要导入?为什么Angular在看到构造函数中指定的DataService类型时不能将此DataService实例提供给构造函数,因为Angular从app.module知道在哪里可以找到DataService类? locations.component中的import 似乎是多余的 .
// locations.component.ts
import { DataService } from '../../../services/dataService';
@Component({
selector: 'app-locations',
templateUrl: './locations.component.html'
})
export class LocationsComponent {
data: any[] = [];
constructor(private dataService: DataService) {
this.data = dataService.load();
}
}
1 回答
我想我理解你的问题 . 这不是为什么需要进口但它是:
从技术上讲,您不必在模块中指定服务的导入 .
@Component
属性可以采用选项providers
值,您可以指定组件的依赖项 . 如果这样做,则不必在模块中声明与模块中的依赖项相同的服务 .您在模块中指定它的原因是使用角度依赖注入框架在模块中注册服务 . 否则,每次要注入相同类型时,都必须执行上述操作(在组件级别注册) . 通过在模块级别注册该类型,它还将注入相同的服务实例,从而有效地创建类似单一的模式 .