我有一个离子2应用程序,其中一个组件从服务中检索client
,并将其作为其子女组件的输入。儿童组件不断丢弃错误,因为当初始化时,client
仍然不确定。
parent
@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
?
请尝试以下您的父部件中的更改
@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种将异步数据传递到Angular 2 子组件的方法,以了解有关问题的更多信息。