我有一个Ionic 2应用程序,其中一个组件从服务中检索client
并将其作为输入提供给它的子组件。子组件不断抛出错误,因为在初始化时,client
仍未定义。
父
@Component({
template: `
<client-generic [client]="client"></client-generic>
`,
})
export class TabComponent {
client:any;
client_id:any;
token:any;
current_user:any;
constructor(private params: NavParams, private clientService: ClientService) {
this.client_id = params.get("client_id")
this.current_user = params.get("current_user")
this.token = this.current_user.auth_token
this.clientService.newGetClient(this.client_id, this.token).subscribe(client => {
this.client = client;
// Logs properly
console.log(this.client);
});
}
}
儿童
@Component({
templateUrl: 'client-generic.html',
selector: 'client-generic'
})
export class ClientGenericPage {
@Input() client: any;
constructor(
public navCtrl: NavController, public navParams: NavParams,
public modalController: ModalController, private clientService: ClientService) {
// Logs undefined
console.log("Client", this.client)
}
}
ngOnInit() {
// also logs undefined
console.log(this.client);
}
我可以做些什么来确保在孩子中定义client
?
答案 0 :(得分:2)
请尝试在您的父组件中进行以下更改
@Component({
template: `
<client-generic [client]="client" *ngIf="!isLoading"></client-generic>
`,
})
export class TabComponent {
client:any;
client_id:any;
token:any;
current_user:any;
isLoading: boolean = true;
constructor(private params: NavParams, private clientService: ClientService) {
this.client_id = params.get("client_id")
this.current_user = params.get("current_user")
this.token = this.current_user.auth_token
this.clientService.newGetClient(this.client_id, this.token).subscribe(client => {
this.client = client;
this.isLoading = false;
// Logs properly
console.log(this.client);
});
}
}
您可以阅读此3 Ways to Pass Async Data to Angular 2+ Child Components以了解有关此问题的更多信息。