在路由传值中,除了从开始路由到目标路由传值之外,还可以从目标路由传值到开始路由。
意思就是从开始路由传值到目标路由成功之后,执行完操作之后又从目标路由返回到了开始路由并携带参数。
一、起始路由向目标路由传递参数
- 获取路由对象
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
- 注入
constructor(
public router: Router,
public activatedRoute: ActivatedRoute
) {}
- 获取当前激活的路由
this.nowRouter = this.activatedRoute['_routerState'].snapshot.url;
- 跳转并传参
// 详情
FaultDetails(item: any) {
const routerParams: NavigationExtras = {
queryParams: {
nowRouter: this.nowRouter, // 字符串
nowRowTableData: JSON.stringify(item), // 对象
searchForm: JSON.stringify(this.searchForm) // 对象
}
};
this.router.navigate(['/faultDetails'], routerParams);
}
二、目标路由接收参数
- 获取路由对象
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
- 获取参数
ngOnInit() {
this.activatedRoute.queryParams.subscribe((data: any) => {
const nowRowTableData = JSON.parse(data.nowRowTableData);
const searchForm = JSON.parse(data.searchForm);
this.searchForm = searchForm;
// 父级路由
if (data.nowRouter) {
// 截取路由,否则报错,如果用到传递过来的路由并返回的时候携带参数,路由可能会不匹配,是因为路由后面多了一些参数,需要截取(第一次ok,第二次失败)
const index = data.nowRouter.indexOf('?');
if (index > 0) {
const routerUrl = data.nowRouter.substring(0, index);
this.parentRouter = routerUrl;
} else {
this.parentRouter = data.nowRouter;
}
}
// 当前的故障列表数据
this.faultListData = nowRowTableData;
// 调用故障详情
this.getFaultDetails(nowRowTableData.RelationGUID);
// 申请状态
this.applyProState = nowRowTableData.ApplyProState;
// 是否撤销
this.isCancel = nowRowTableData.IsCancel;
});
}
三、目标路由向起始路由传递参数
- 获取路由对象
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
- 注入同上
- 传参
// 返回到父级
backParent() {
const routerParams: NavigationExtras = {
queryParams: {
searchForm: JSON.stringify(this.searchForm),
}
};
this.router.navigate([this.parentRouter], routerParams);
}
四、起始路由接收参数
// 获取当前激活的路由传递过来的数据
this.activatedRoute.queryParams.subscribe((data: any) => {
// 传递过来的搜索条件
if (JSON.stringify(data) !== '{}') {
const searchForm = JSON.parse(data.searchForm);
// this.searchForm.startTime = searchForm.startTime;
// this.searchForm.endTime = searchForm.endTime;
// this.searchForm.ferSiteID = searchForm.ferSiteID;
this.searchForm = searchForm;
this.searchOrderData(null);
}
});