我正在学习angular 6和typescript,并且在多个组件之间传递数据时遇到一些问题 . 看起来在“expense-box.component.ts”组件中,ngOnInit方法中的“this.participants”为null / empty . 所以我没有得到任何数据 .
第一个(父)组件 - expense.component.ts :
public participants = new Array<Participant>();
getParticipants(): void {
this.participantService
.getParticipants(token)
.subscribe(participants => (this.participants = participants));
}
参与者服务 - participant.service.ts (在getParticipants方法中显示什么)
getParticipants(token: string): Observable<Participant[]> {
return this.http.get<Participant[]>(`${this.url}/${token}`).pipe(
tap(() => this.log(`Participants assigned to trip with token: ${token} fetched`)),
catchError(this.handleError<Participant[]>('getParticipants'))
);
}
这是html模板 - expense.component.html :
<app-expense-box *ngIf="selectedSplitTab == 1" [participants]="participants"></app-expense-box>
expense-box.component.ts
export class ExpenseBoxComponent implements OnInit {
@Input() participants: Participant[];
public equallyList = new Array<Equally>();
ngOnInit() {
this.participants.forEach(element => {
this.equallyList.push(new Equally(element.id, false, element.name));
});
}
addExpense(): void {
this.expense.equallyTab = this.equallyList;
this.expenseService.addExpense(this.expense).subscribe(() => console.log('Expense added!'));
}
}
这是html模板 - expense-box.component.html
<app-split-differently [equallyList]="equallyList" [splitEqually]="splitEqually"></app-split-differently>
这是儿童组件 - split-differently.component.ts
export class SplitDifferentlyComponent implements OnInit {
@Input() splitEqually: boolean;
@Input() equallyList: Equally[];
public selectedSplitTab = 1;
constructor() {}
ngOnInit() {}
enableSplitTab(selectedTab: number): void {
this.selectedSplitTab = selectedTab;
}
}
这是html模板 - split-differently.component.html
<div class="form-check" *ngFor="let item of equallyList">
<input class="form-check-input" type="checkbox" value="" id="equallyTabParticipant{{item.userId}}" checked="{{item.checked}}">
<label class="form-check-label" for="equallyTabParticipant{{item.userId}}">
{{ item.userName }}
</label>
<hr>
</div>
最后,我希望在将其发送到后端时具有EquallyList的当前状态 . 现在什么都没有显示,因为我做错了(控制台没有记录任何错误) .
感谢评论中的答案,现在一切都正确显示 . 我已选中一个复选框(其他未选中),单击保存按钮,所有“已选中”都设置为false,因此值未正确绑定 . 这是带有json的屏幕,它被发送到后端:
1 回答
当您尝试在ngOnInit()方法中访问它时,您的输入可能未收到数据 .
您应该使用setter方法输入,然后在该方法中执行您的操作 . 或者,您可以使用ngOnChanges()钩子
对于前者:与二传手
与ngOnchanges