简体   繁体   English

为什么添加构造函数会在此处破坏Angular 2?

[英]Why does adding a constructor break Angular 2 here?

I am attempting to define a TypeScript class called NavItem that I want to hold a title and url. 我正在尝试定义一个名为NavItem的TypeScript类,我想保留标题和URL。 I find that if I define this class and instantiate it using object notation {title: "foo", url: "bar"} it works perfectly, but as soon as I add a constructor (even if I don't immediately use it) it completely breaks: 我发现,如果我定义此类并使用对象表示法{title: "foo", url: "bar"}实例化它{title: "foo", url: "bar"}则它可以正常工作,但是一旦添加构造函数(即使我不立即使用它)它完全坏了:

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

@Component({
    selector: 'nav-item',
    templateUrl: './views/navitem.html',
})
export class NavItem {
    @Input() title: String = "default title";
    @Input() url: String;

    // if I comment the following out it works fine:
    constructor(inTitle: String, inUrl: String) {
        this.title = inTitle;
        this.url = inUrl;
    }
}

If I put the constructor in, I get this in my page: 如果将构造函数放入,则会在我的页面中看到:

EXCEPTION: No provider for String! 例外:没有String的提供者! (NavItem -> String) in [navItems in TopNav@2:11] (TopNav @ 2:11中的navItems)中的(NavItem-> String)

If I put the constructor in, I get this in my page: 如果将构造函数放入,则会在我的页面中看到:

This is because angular is supposed to instantiate the controller for you . 这是因为angular应该为您 实例化控制器。 You don't do new FooController , angular does. 您不需要做new FooController ,而可以做角度的。 So any constructor parameters must have a corresponding provider registered with angular. 因此,任何构造函数参数都必须具有向angular注册的相应提供程序。

The constructor is used for DI with components. 构造函数用于带有组件的DI。 If you want to pass in the values of title and url you would do the following. 如果要传递title和url的值,请执行以下操作。

<nav-item [title]="Sometitle" [url]="http://someurl.com">

Angular will hook it up for you Angular会为您连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM