javascript - 如何将数据从一个组件传递到另一个组件以进行编辑表单?

标签 javascript angular typescript

目前,我有一个模态 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/

相关文章:

javascript - Visual Studio 编译器 'syntax error' 关于 javascript 的警告

javascript - 从自定义组件中获取除 "value"之外的 props 值?

javascript - JS : What's the difference between a ! 闭包和()闭包?

javascript - 无法使用 rivetJs 显示 JSON 对象数组中的值?

Angular HTTP 拦截器订阅 observable 然后返回 next.handle 但抛出 TypeError : You provided 'undefined'

.net - 具有 Angular 前端和 .NET 后端的 Azure SSO 的 SAML 配置

angular - Ionic 4/Capacitor PWA 应用程序不会更新 Firebase 托管的最新内容

javascript - Typescript class.default 不是构造函数

angular - 在 Angular nx 项目中导入 glsl 文件

angular - 如何在 ionic 2 注销后隐藏侧边菜单