通过模板将数据从父级传递给子级

Passing data from Parent to Child via template

我有一个如下的模板用户:

<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>

我的应用列表组件如下所示:

export class ListComponent implements OnInit {
  @Input() user: string;

  constructor() { }

  ngOnInit() {   
    console.log(this.user);
  }  

}

页面上正确显示了用户名和信誉。但是,用户名值未正确传递给子组件 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
          }
        }
      )
    ));
  }

}

应该是,

<app-list [user]="username"></app-list>

或者你可以使用 @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;
    });