javascript - angularjs2中導入其他模組的對象,編譯提示屬性不存在對像中
给我你的怀抱
给我你的怀抱 2017-05-18 10:57:37
0
1
597

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沒多久,對它還不熟悉,望指教。

给我你的怀抱
给我你的怀抱

全部回覆(1)
伊谢尔伦

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板