Mot*_*ine 130 routing angular angular-router
无论如何使用router.navigate将数据作为参数发送?我的意思是,像这个例子,你可以看到路由有一个数据参数,但这样做它不起作用:
this.router.navigate(["heroes"], {some-data: "othrData"})
Run Code Online (Sandbox Code Playgroud)
因为某些数据不是有效参数.我怎样才能做到这一点?我不想用queryParams发送参数.
Deb*_*ahK 392
关于这个主题存在很多混淆,因为有很多不同的方法可以做到这一点.
以下是屏幕截图中使用的相应类型:
private route: ActivatedRoute
private router: Router
Run Code Online (Sandbox Code Playgroud)
1)所需的路由参数:
2)路由可选参数:
3)路由查询参数:
4)您可以使用服务将数据从一个组件传递到另一个组件,而根本不使用路由参数.
有关示例,请参阅:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
我这里有一个这样的人:https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p = preview
private route: ActivatedRoute
private router: Router
Run Code Online (Sandbox Code Playgroud)
Vég*_*ánd 85
Angular 7.2.0附带了一种新方法
https://angular.io/api/router/NavigationExtras#state
发送:
this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Run Code Online (Sandbox Code Playgroud)
收到:
constructor(private router: Router) {
console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到一些额外的信息:
https://github.com/angular/angular/pull/27198
上面的链接包含这个例子,它可能有用:https: //stackblitz.com/edit/angular-bupuzn
dev*_*ish 15
最新版本的angular(7.2 +)现在可以选择使用NavigationExtras传递其他信息。
家庭组件
import {
Router,
NavigationExtras
} from '@angular/router';
const navigationExtras: NavigationExtras = {
state: {
transd: 'TRANS001',
workQueue: false,
services: 10,
code: '003'
}
};
this.router.navigate(['newComponent'], navigationExtras);
Run Code Online (Sandbox Code Playgroud)
newComponent
test: string;
constructor(private router: Router) {
const navigation = this.router.getCurrentNavigation();
const state = navigation.extras.state as {
transId: string,
workQueue: boolean,
services: number,
code: string
};
this.test = "Transaction Key:" + state.transId + "<br /> Configured:" + state.workQueue + "<br /> Services:" + state.services + "<br /> Code: " + state.code;
}
Run Code Online (Sandbox Code Playgroud)
输出量
希望这会有所帮助!
小智 6
你可以用它.Angular2 +/4/5 - 使用数据导航 https://github.com/Hipparch/Angular2-navigate-with-data
我需要访问其中的数据,但由于循环依赖,CustomRouteReuseStrategy我无法在那里注入数据,但您也可以使用该对象来读取状态。RouterLocation
Send:
this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Receive:
import { Location } from '@angular/common';
constructor(private location: Location) {
console.log(this.location.getState().example); // should log out 'bar'
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148183 次 |
| 最近记录: |