我正在看一个样例Angular 2项目,并插入了一些代码,试图从传递给嵌套子组件的电影对象中提取值。
在父代码中,我有以下内容:
<div class="col-sm-6 col-md-4 col-lg-3 col-xs-6" *ngFor="let movie of movies; let i = index;">
<movie-card [movie]="movie"></movie-card>
</div>在我的电影卡.组件.ts文件中,我有这个代码:
import { Component, Input } from '@angular/core';
@Component({
selector: 'movie-card',
templateUrl: './movie-card.component.html',
styleUrls: ['./movie-card.component.css']
})
export class MovieCardComponent {
@Input()
movie: Object;
constructor() {
console.log('movie : ' + this.movie);
}
}我的Chrome控制台的输出是:
20 movie : undefined movie-card.component.ts:15 但是在电影卡中。组件.html
{{movie.Name}}html将输出电影名称。
我想像这样将movie.Name值发送到我的服务。
_anatomyService.getImage(this.movie.Name);然而,电影的价值是不确定的。我有什么不明白的吗?
提前谢谢你。
发布于 2016-12-17 16:30:12
您可以对您的值使用集合
import { Component, Input } from '@angular/core';
@Component({
selector: 'movie-card',
templateUrl: './movie-card.component.html',
styleUrls: ['./movie-card.component.css']
})
export class MovieCardComponent {
@Input()
set movie(movie: Object){
console.log(movie);
//asign it to a value or do something with it
}
}发布于 2016-12-17 15:47:25
您的电影卡.组件.ts应该是这样的。
import { Component, Input, OnInit } from '@angular/core'; <-- add OnInit
@Component({
selector: 'movie-card',
templateUrl: './movie-card.component.html',
styleUrls: ['./movie-card.component.css']
})
export class MovieCardComponent {
@Input()
movie: Object;
constructor() { }
ngOnInit() { <-- your this.movie should be in ngOnInit lifecycle hook
console.log('movie : ' + this.movie);
}
}有关更多生命周期挂钩http://learnangular2.com/lifecycle/,请查看此链接
发布于 2016-12-17 14:43:57
构造函数内部没有初始化的输入值。你必须等到ngOnInit()
ngOnInit() {
console.log('movie : ' + this.movie);
}另请参阅此处有关angular2生命周期的更多详细信息
https://stackoverflow.com/questions/41196077
复制相似问题