2017-09-13 91 views
0

我爲什麼會在這個代碼中的錯誤錯誤訪問定義對象的實例的屬性

錯誤源於(其作爲代碼主要是這裏的代碼,你必須從角文檔熟悉)與星行...

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

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

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    title = 'Tour of Heroes'; 
    hero: Hero = { 
    id: 1, 
    name: 'Windstorm' 
    }; 

    if (hero.name === 'prekazi') { // <--****************** 
    // do something 
    } 
} 

的錯誤是

Failed to compile. 

/Users/.../Desktop/angular-tour-of-heroes/src/app/app.component.ts (20,11): ',' expected. 

這是由於該行:

if (hero.name === 'prekazi') { 

爲什麼我們不能用點符號來得到英雄實例的屬性?有人可以友好地指點我在這裏錯過了什麼嗎?

回答

1

您的代碼在類內,但不在類的方法內。例如,如果您將其添加到ngOnInit,它就會生效:

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

    ngOnInit() { 
     if (this.hero.name === 'prekazi') { // <--****************** 
      alert('That\'s my hero! ') 
     } 
    } 
} 
+0

對!我真是個小丑!謝謝你的收穫!它也是這樣工作的:''constructor(){ if(this.hero.name ==='prekazi'){ alert('That'is my hero!') } }' –

+0

但是當我通過預期賓果遊戲字符串'prekazi',我沒有得到警報!角度是否以不同的方式做出了古老的js警報? –

+0

@AverageJoe對於這個例子來說,構造函數也不錯。一般來說,我傾向於使用像'ngOnInit'這樣的鉤子,因爲當所有其他數據都可用時(例如通過'Input'將數據傳遞到組件中)。 –