【问题标题】:Angular 2 error:角度 2 错误:
【发布时间】:2016-03-22 05:40:17
【问题描述】:

使用 Angular 2 并尝试让这个简单的代码工作。 但我一直收到以下错误:

异常:无法解析 Tab(未定义)的所有参数。确保 它们都有有效的类型或注释。

到目前为止,ng2 没有将 constructor(tabs:Tabs) {… 注入到构造函数中

这是完整的代码:

///<reference path="../../typings/zone.js/zone.js.d.ts"/>

import {Component, Input} from 'angular2/core';

@Component({
    selector: 'tab',
    template: `
    <ul>
      <li *ngFor="#tab of tabs" (click)="selectTab(tab)">
        {{tab.tabTitle}}
      </li>
    </ul>
    <ng-content></ng-content>
  `,
})
export class Tab {
    @Input() tabTitle: string;
    public active:boolean;
    constructor(tabs:Tabs) {
        this.active = false;
        tabs.addTab(this);
    }
}

@Component({
    selector: 'tabs',
    directives: [Tab],
    template: `
    <tab tabTitle="Tab 1">
        Here's some content.
    </tab>
  `,
})

export class Tabs {
    tabs: Tab[] = [];
    selectTab(tab: Tab) {
        this.tabs.forEach((myTab) => {
            myTab.active = false;
        });
        tab.active = true;
    }

    addTab(tab: Tab) {
        if (this.tabs.length === 0) {
            tab.active = true;
        }
        this.tabs.push(tab);
    }
}

发送

肖恩

【问题讨论】:

    标签: angular


    【解决方案1】:

    这是因为您的 Tabs 类是在您的 Tab 类和 classes in javascript aren't hoisted 之后定义的。

    所以你必须使用forwardRef 来引用一个尚未定义的类。

    export class Tab {
        @Input() tabTitle: string;
        public active:boolean;
        constructor(@Inject(forwardRef(() => Tabs)) tabs:Tabs) {
            this.active = false;
            tabs.addTab(this);
        }
    }
    

    【讨论】:

    • 或者在两个模块/命名空间中声明类。这允许您持有对将包含实际类的对象的引用,并且当 Angular 来取消引用这些类时,它们已经被创建了。
    • 谢谢!!!!没有考虑排序,所以习惯了es3中的函数和std提升
    【解决方案2】:

    您有两种解决方案: 在引导程序中全局注入您的 Tabs 类:

    bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]);
    

    在使用绑定属性在本地注入选项卡时,

    @Component({
        selector: 'tab',
        bindings: [Tabs],   // injected here
        template: `
        <ul>
          <li *ngFor="#tab of tabs" (click)="selectTab(tab)">
        [...]
    

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 2016-08-19
      • 2016-11-20
      • 2023-03-04
      • 2018-12-31
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多