-1

我有一个提交功能,当我提交时,我从服务器获取数据。我希望我收到的数据将传递给其他组件。

这是我的功能

  submitForm(partner, manager, taxDevision, taxYear, standard, date) {
    const type = 1;
    if (partner && manager && taxDevision && taxYear && standard && date.value !== null && this.addValue !== '') {
      const day = date.value.getDate();
      const month = date.value.getMonth() + 1;
      const year = date.value.getFullYear();
      const newDate = `${year}-${month}-${day}`;
      this.reportsService.createNewReport(this.addValue, type, taxYear, newDate, (data) => this.onCreateReportSuccess(data));
    } else {
      this.errorLabel = 'Fill all field';
    }
  }
  onCreateReportSuccess(data) {
    console.log(data);
    this.dialogRef.close();
    this.router.navigate(['/kit']);
  }
}
4

2 回答 2

0

我找到了一个解决方案:

  submitForm(partner, manager, taxDevision, taxYear, standard, date) {
    const type = 1;
    if (partner && manager && taxDevision && taxYear && standard && date.value !== null && this.addValue !== '') {
      const day = date.value.getDate();
      const month = date.value.getMonth() + 1;
      const year = date.value.getFullYear();
      const newDate = `${year}-${month}-${day}`;
      this.reportsService.createNewReport(this.addValue, type, taxYear, newDate, (data) => this.onCreateReportSuccess(data));
    } else {
      this.errorLabel = 'Fill all field';
    }
  }
  onCreateReportSuccess(data) {
    this.dialogRef.close();
    this.router.navigate(['/kit'], { queryParams: data[0] });
  }

获取 Kit 组件上的数据:

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
    this.route
      .queryParams
      .subscribe(reportData => {
        console.log(this.reportData);
      });
  }
于 2019-10-06T14:39:15.893 回答
-1

看下面的服务实现

export class ReportService{
    postedReport: BehaviorSubject<any> = new BehaviorSubject<any>(null);
    ...
    createNewReport(...){
        return this.http.post(...).pipe(tap((response)=>{
            this.postedReports.next(response);
        }));
    }

}

使用 rxjs管道点击我们插入异步响应并将其存储在BehaviorSubject中。

然后从您的原始代码中复制此摘录,

export class componentA{
    constructor(public reportService: ReportService,...){}
    ...
    submitForm(){
        this.reportService.createNewReport(...)
        .toPromise().then(() => console.log('post'));
    }
}

最后,我们可以在componentB中读取我们的服务响应值

export class componentB{
    constructor(public reportService: ReportService,...){
        let sub = this.reportService.postedReport.subscribe((report)=>{

                    console.table(report);
                  })
    }
    ...
    printReport(){
        console.log(this.reportService.postedReport.value)
    }
}

请注意,这些示例不完整,我们使用了 [...]

作为对 OP 需要绑定到组件 B 中组件 A 的服务调用响应的响应。不使用建议的导航功能,因为我们在同一个角度应用程序中,服务也可以工作,并且具有将导航与数据查询和存储分离的优势。

于 2019-10-06T13:19:33.257 回答