我有一个模板用户,如下所示:
<div class="jumbotron">
<div class="container">
<h2><i class="fa fa-user"></i> {{username}}</h2>
<p><i class="fa fa-star"></i> {{reputation}}</p>
</div>
</div>
<app-list user={{username}}"></app-list>
我的app-list组件如下所示:
export class ListComponent implements OnInit {
@Input() user: string;
constructor() { }
ngOnInit() {
console.log(this.user);
}
}
页面上正确显示了用户名和信誉。但是,用户名值未正确传递到子组件app-list,因为它只打印出一个空字符串。
如何将用户名传递给app-list组件?
修改
用户组件如下所示:
export class UserComponent implements OnInit {
private username: string;
private reputation: number;
constructor(private route: ActivatedRoute, private apiService: ApiService) {
}
ngOnInit() {
this.route.params.subscribe((params: Params) => (
this.apiService.getUser(params['username']).subscribe((response: Response) => {
console.log(response.json());
this.username = response.json().username;
this.reputation = response.json().reputation;
}, (error) => {
if (error.status === 404) {
// Todo: redirect to 404 page
}
}
)
));
}
}
答案 0 :(得分:1)
应该是,
<app-list [user]="username"></app-list>
答案 1 :(得分:1)
或者,您可以使用@ViewChild()
装饰器来实现以下
export class UserComponent implements OnInit {
@ViewChild(AppListCopmonent) appList: AppListComponent;
ngOnInit() {
this.appList.user = this.username
}
}
基于聊天更新:在分配值之前,检查数据是否为
this.apiService.getUser(params['username']).subscribe((response: Response) => {
if(response){
console.log(response.json());
this.username = response.json().username;
this.reputation = response.json().reputation;
});