目前,我有一个模态 Material 对话框窗口,要求用户输入数字,然后单击搜索。在搜索时,它从 api 调用获取数据并返回响应对象。我想使用响应对象来填充新页面(编辑表单)。
我的问题是,如何将数据(特别是用户在 Material 对话框组件上输入的数字)传递到另一个组件,以便它可以获取 api 调用结果,或者如何将我的响应对象传递给我的编辑从对话框?
例如
这是我的搜索功能:
search(searchNumber) {
if (this.selectedOption === 'Bill Number') {
this._transactionService.findExistingTransactionByBillNumber('U001', searchNumber)
.subscribe(data => this.transactionResponse = data);
console.log(JSON.stringify(this.transactionResponse));
this.router.navigate(['/edit-transaction-portal']);
} else {
this._transactionService.findExistingTransactionByTransactionNumber('U001', searchNumber)
.subscribe(data => this.transactionResponse = data);
console.log(JSON.stringify(this.transactionResponse));
this.router.navigate(['/edit-transaction-portal']);
}
}
我希望能够 1) 传递我在此处获得的响应对象或传递用户输入的 searchNumber,以便我可以在编辑表单组件中进行查找。我需要将此组件中的任一组件传递到我导航到的新组件。
编辑:接受的解决方案显示了如何将查询参数添加到 this.router.navigate() 以及如何通过订阅 activateRoute 来检索它,这是与另一篇 SO 帖子中确定的方法不同的方法。
最佳答案
您可以传递号码(账单/交易)
this.router.navigate(['/edit-transaction-portal'], { queryParams: { bill: 'U001' } });
this.router.navigate(['/edit-transaction-portal'], { queryParams: { transaction: 'U001' } });
然后在您的组件(edit-transaction-portal)
中点击 api 来获取数据。在组件中,您应该在构造函数中包含 ActivatedRoute
。它会是这样的:
isBill: boolean;
isTransaction: boolean;
number: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sub = this.route
.queryParams
.subscribe(params => {
this.isBill = params['bill'] != undefined;
this.isTransaction = params['transaction'] != undefined;
this.number = this.isBill ? params['bill'] : params['transaction'];
// Call API here
});
}
关于javascript - 如何将数据从一个组件传递到另一个组件以进行编辑表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548623/