搜尋

首頁  >  問答  >  主體

javascript - angularjs2中導入其他模組的對象,編譯提示屬性不存在對像中

angularjs2中導入其他模組的物件(該物件內嵌套另一個物件)並使用,編譯時控制台提示該物件中不包含所嵌套的物件所以編譯不通過,但是如果將另一個模組中的物件聲明直接複製到同一個文件下,就一切正常。

控制台提示的錯誤如下:

#問題程式碼如下:

//exercise-detail.component.ts
import { Component } from '@angular/core';

import { Exercise } from './exercise';


let exercise: Exercise = {
    id: 1,
    name: 'bench press',
    exerciseSets: [{
        id: 1,
        num: 1,
        previousWeight: 0,
        weight: 10,
        reps: 12,
        isFinish: true
    },{
        id: 2,
        num: 2,
        previousWeight: 0,
        weight: 10,
        reps: 12,
        isFinish: false
    }]
};

@Component({
    selector: 'exercise-detail',
    template: `
       <table border='1'>
           <tr>
               <td>finish?</td>
               <td>{{exercise.exerciseSets[1].isFinish}}</td>
           </tr>
       </table>
    `
})
export class ExerciseDetailComponent {

    exercise = exercise;
}
    
//exercise.ts
export class ExerciseSet {
    id: number;
    num: number;
    previousWeight: number;
    weight: number;
    reps: number;
    isFinish: boolean;
}

export class Exercise {

    id: number;
    name: string;
    exerciseSets: ExerciseSet[];
}

當兩個檔案中的程式碼合併到一個檔案後,就可以透過編譯,輸出正確。
合併後程式碼如下:

//exercise-detail.component.ts
import { Component } from '@angular/core';

export class ExerciseSet {
    id: number;
    num: number;
    previousWeight: number;
    weight: number;
    reps: number;
    isFinish: boolean;
}

export class Exercise {

    id: number;
    name: string;
    exerciseSets: ExerciseSet[];
}

let exercise: Exercise = {
    id: 1,
    name: 'bench press',
    exerciseSets: [{
        id: 1,
        num: 1,
        previousWeight: 0,
        weight: 10,
        reps: 12,
        isFinish: true
    },{
        id: 2,
        num: 2,
        previousWeight: 0,
        weight: 10,
        reps: 12,
        isFinish: false
    }]
};

@Component({
    selector: 'exercise-detail',
    template: `
       <table border='1'>
           <tr>
               <td>finish?</td>
               <td>{{exercise.exerciseSets[1].isFinish}}</td>
           </tr>
       </table>
    `
})
export class ExerciseDetailComponent {

    exercise = exercise;
}

我相信這問題很容易解決,不是語法錯誤和邏輯錯誤,應該是Typescript對導入文件有要求,我剛用Typescript沒多久,對它還不熟悉,望指教。

给我你的怀抱给我你的怀抱2784 天前611

全部回覆(1)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-05-18 10:59:37

    我也寫過這樣的, 只不過我賦值的時候是在 constrctor裡面 new了一下,就ok了

    回覆
    0
  • 取消回覆