簡體   English   中英

Angular 5 -> 組件中的提供者

[英]Angular 5 -> providers in Component

我對 Angular 5 組件有疑問,我的組件如下所示:

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] (例如創建登錄組件

所以主要的區別是你將它注入到你的組件中,而教程是將它注入到模塊中。

像下面的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

如果您不想在組件中定義提供者(您的服務),則應將其添加到模塊中的提供者部分

這里是概述

在通過您的鏈接的課程中,作者使用 ng 生成組件、服務等,因此它會自動創建以下結構(在模塊級別定義提供程序)。

不,您不需要該行,您可以將提供者添加到您的組件所屬的同一模塊中,並通過構造函數注入服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM