2017-07-02 103 views
1

从父将数据传递给孩子,我有一个模板,用户喜欢以下内容:通过模板

​​

我的应用程序列表组件的样子:

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

    constructor() { } 

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

} 

用户名和声誉是正确显示在这一页。但是,用户名值未正确传递到子组件应用程序列表,因为它只打印出一个空字符串。

如何将用户名传递给应用程序列表组件?

编辑

用户组件的样子:

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 
      } 
     } 
    ) 
    )); 
    } 

} 

回答

1

它应该是,

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

我已经试过这一点。控制台打印'undefined' – isADon

+0

显示你声明如何在user.component中使用 – Sajeetharan

+0

请参阅编辑 – isADon

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; 
    }); 
+0

我不知道这将如何帮助。我试图从父母到孩子发送一个价值。我将如何访问ListComponent中的值? – isADon

+0

这将工作。你想看演示? – Aravind