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没多久,对它还不熟悉,望指教。
我也写过这样的, 只不过我赋值的时候是在 constrctor里面 new了一下,就ok了