我对Angular 5 Components有疑问,My Component看起来像这样:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AuthService } from './../auth/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [FormBuilder, AuthService] // is this line needed?
})
export class LoginComponent implements OnInit {
constructor(private fb: FormBuilder, private authService: AuthService) { }
ngOnInit() {
}
}
没有提供商行:[FormBuilder,AuthService] 我发现以下异常:
NullInjectorError: No provider for FormBuilder!
如果我添加提供商:[FormBuilder,AuthService] ,那么一切正常。 我现在的问题是,如果这一行真的是必要的,因为我在没有提供者行的教程中看到了组件:[FormBuilder,AuthService] (例如Creating the Login component)
答案 0 :(得分:2)
所以主要区别在于您将它注入到组件中,教程将其注入模块中。
与AppModule
的以下示例相似:
import { AuthService } from './../auth/auth.service';
import {FormsModule } from "@angular/forms";
@NgModule({
modules: [
FormsModule
],
providers: [
AuthService
]
})
export class AppModule { }
您可以在此处看到注入方式的不同之处:https://stackoverflow.com/a/42562446/3329836
答案 1 :(得分:0)
如果您不想在组件中定义提供程序(您的服务),则应将其添加到模块中的providers部分
HERE概述
在通过链接的课程中,作者使用ng来生成组件,服务等,因此它会自动创建以下结构(在模块级别定义提供程序)。
答案 2 :(得分:0)
不,您不需要该行,您可以将提供程序添加到组件所属的同一模块中,并通过构造函数注入服务。