为什么类别的顺序在角度2分量中很重要? [英] Why the order of classes matters in angular 2 component?

查看:31
本文介绍了为什么类别的顺序在角度2分量中很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注angular2官方教程,并打算制作"2.The Hero Editor".在app.component.ts文件中,我有两个类Hero和AppComponent.

I'm following angular2 official tutorial and about to make '2.The Hero Editor'. In app.component.ts file, I have two class, Hero and AppComponent.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>{{hero.name}} details!</h2>
    <div><label>id: </label>{{hero.id}}</div>
    <div>
      <label>name: </label>
      <input [(ngModel)]="hero.name" placeholder="name">
    </div>
    `
})

export class Hero {
  id: number;
  name: string;
}

export class AppComponent {
  title = 'Tour of Heroes';
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };
}

因为AppComponent的成员类型为'Hero'类,所以我认为Hero必须在AppComponent之前声明.但是,然后出现了奇怪的错误消息,如下所示.

Because AppComponent has member type of 'Hero' class, I thought Hero must declared before the AppComponent. But, then the weird error message was appear like below.

EXCEPTION: No Directive annotation found on AppComponent

当我将Hero类移到AppComponent的下一个时,它可以工作...而且我不知道为什么.任何意见,将不胜感激.谢谢.

And when I moved Hero class to next of AppComponent, it works... and I don't know why. Any advice would be appreciated. Thanks.

推荐答案

装饰器(例如, @Component )在紧随其后的对象上工作.您的代码应为:

Decorators (@Component for example) work on the objects that are right after them. Your code should be:

@Component({...})
class Hero {}

@Component({...})
class AppComponent {}

如果您查看 JavaScript 示例:

  app.AppComponent =
    ng.core.Component({
    })
    .Class({
    });

您会明白为什么...

you can see why...

此外,如果您在单个文件中编写多个类,则顺序很重要.JavaScript是按顺序执行的,如果您请求尚未定义的内容,则会收到错误消息.

Also, if you're write multiple classes in single file, order matters. JavaScript is executed sequentially, if you ask for something that's not yet defined, you'll get an error.

这篇关于为什么类别的顺序在角度2分量中很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆