我有一个提交功能,当我提交时,我从服务器获取数据。 我希望我收到的数据将传递给其他组件。
这是我的职责
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']);
}
}
答案 0 :(得分: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] });
}
获取套件数据:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route
.queryParams
.subscribe(reportData => {
console.log(this.reportData);
});
}
答案 1 :(得分:-1)
查看以下服务实现
export class ReportService{
postedReport: BehaviorSubject<any> = new BehaviorSubject<any>(null);
...
createNewReport(...){
return this.http.post(...).pipe(tap((response)=>{
this.postedReports.next(response);
}));
}
}
使用rxjs pipe和tap,我们将插入异步响应并将其存储在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的要求,需要绑定到componentA的 组件B中的服务呼叫响应。不使用建议的导航功能,因为我们在同一个角度应用程序中,所以服务也可以工作,并且具有将导航与数据查询和存储区分开的优势。