没有共享组件的提供商

问题描述:

我的应用程序有几个功能模块,使用几个常见的@Component s。因此,我试图将所有这些共享组件移动到'Widget Module`中,如angular.io FAQ链接here所述。没有共享组件的提供商

然而,当我尝试这个小部件添加到我的模板之一,我得到:

Error in package:./src/app/tracker/clients/client-detail.component.ts 
class ClientDetailComponent - inline template:28:8 caused by: 
No provider for String! 

这里是我尝试使用该功能模块内的共享组件:

@Component({ 
    moduleId: module.id, 
    selector: 'client-detail', 
    template: ` 
<save-button id="save-button" (click)="saveClient()" [isSaving]="isSaving" [disableSave]="disableSave"></save-button> 
` 
}) 
export class ClientDetailComponent implements OnInit { 
    isSaving: boolean = false; 
    disableSave: boolean = false; 

    constructor() { } 

    ngOnInit() {} 

    saveClient() { 
    this.isSaving = true; 
    // do some work... 
    this.isSaving = false; 
} 

这里的功能模块模块:

import {SharedWidgetModule} from "../shared/shared-widget.module"; 

@NgModule({ 
    imports: [ 
    CommonModule, 
    FormsModule, 
    TrackerRoutingModule, 
    SharedWidgetModule 
    ], declarations: [ 
    TrackerComponent, 
    TrackerHomeComponent, 

    // Clients 
    ClientsComponent, 
    ClientsHomeComponent, 
    ClientShieldComponent, 
    ClientDetailComponent, 

    // EndClients 
    EndClientListComponent 
    ], providers: [ 
    BackendService, 
    ClientsService 
    ] 
}) 
export class TrackerModule { } 

<save-button>组件出现从SharedWidgetModule:

import {NgModule} from "@angular/core"; 
import {SaveButtonComponent} from "./save-button/save-button.component"; 
import {CommonModule} from "@angular/common"; 

@NgModule({ 
    imports: [CommonModule], 
    exports: [SaveButtonComponent, CommonModule], 
    declarations: [SaveButtonComponent], 
    providers: [], 
}) 
export class SharedWidgetModule { } 

保存-button.component.html:

<button type="submit" class="btn btn-primary" [disabled]="disableSave || isSaving"> 
    <i *ngIf="isSaving" class="fa fa-refresh fa-spin"></i> 
    <i *ngIf="!isSaving" class="fa {{icon}}"></i> 
    {{name}} 
</button> 

保存-button.component.ts:

import {Component, OnInit, Input} from "@angular/core"; 

@Component({ 
    moduleId: module.id, 
    selector: 'save-button', 
    templateUrl: 'save-button.component.html', 
    styleUrls: ['./save-button.component.scss'] 
}) 
export class SaveButtonComponent implements OnInit { 
    name: string; 
    icon: string; 
    @Input() isSaving: boolean; 
    @Input() disableSave: boolean; 

    constructor(name: string, icon: string) { 
     this.name = name || 'Save'; 
     this.icon = icon || 'fa-floppy-o'; 
    } 

    ngOnInit() { } 
} 

我在做什么错?

你的问题在于对SaveButtonComponentconstructor。对于那些Angular2元素(Component,Directive,Injectable等),构造函数是一个神圣的地方,不应该被纯粹的基元所污染。换句话说,Angular2会尝试使用构造函数中的信息向您的组件注入服务,并且明确nameicon不是服务。

我看你不使用它们的那一刻,你为什么不只是摆脱这些原语并留下您的SavebuttonComponent.constructor()空的?你可以随时在后期设置它们。

+0

完全是这样。我把它们改成'@Input()',没有一切都好。感谢您指出明显。有时显而易见的是最难看到的。 –