没有共享组件的提供者

时间:2016-11-16 00:02:43

标签: angular typescript

我的应用程序有几个功能模块,它们使用了一些常见的@Component。所以我试图将所有这些共享组件移动到' 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() { }
}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的问题出在constructor的{​​{1}}上。对于那些Angular2元素(SaveButtonComponentComponentDirective等),构造函数是一个神圣的地方,不应该仅被原始元素污染。换句话说,Angular2将尝试使用其构造函数中的信息向您的组件注入服务,显然Injectablename不是服务。

我发现你现在还没有使用它们,为什么不放弃这些原语让你的icon空?你总是可以在以后阶段进行设置。