是否有任何方式发送数据作为参数路由器。导航? 我的意思是,像这个例子,你可以看到路由有一个数据参数,但是这样做是不行的:
this.router.navigate(["heroes"], {some-data: "othrData"})
因为some-data不是一个有效参数。我该怎么做呢?我不想用queryParams发送参数。
是否有任何方式发送数据作为参数路由器。导航? 我的意思是,像这个例子,你可以看到路由有一个数据参数,但是这样做是不行的:
this.router.navigate(["heroes"], {some-data: "othrData"})
因为some-data不是一个有效参数。我该怎么做呢?我不想用queryParams发送参数。
当前回答
我需要访问CustomRouteReuseStrategy中的数据,由于循环依赖,我不能在那里注入路由器,但你也可以使用Location对象来读取状态。
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'
}
其他回答
我需要访问CustomRouteReuseStrategy中的数据,由于循环依赖,我不能在那里注入路由器,但你也可以使用Location对象来读取状态。
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'
}
在这个话题上有很多困惑,因为有很多不同的方法来做到这一点。
以下是在以下截图中使用的适当类型:
private route: ActivatedRoute
private router: Router
1)所需路由参数:
2)路由可选参数:
3)路由查询参数:
4)您可以使用服务将数据从一个组件传递到另一个组件,而完全不使用路由参数。
示例参见:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
我这里有一个活塞:https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview
最新版本的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);
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;
}
输出
希望这能有所帮助!
从Angular 15开始,this.router.getCurrentNavigation()可能会返回null,因为该组件是在导航之后实例化的。
另一种方法是从Location (@angular/common)中访问状态
import { Location } from '@angular/common';
constructor(private location: Location) {
location.getState() // do what you want
}
在navigateExtra中,我们只能传递一些特定的名称作为参数,否则将显示如下所示的错误: 对于Ex-,我想在路由器导航中传递客户密钥,我这样传递
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
但它显示一些错误如下:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
解决方案: 我们要这样写:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});