我有如下路由器链接:
<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show'}]">
我想传递参数showTour
。但是,当我这样做时,参数是可见的url
,我想隐藏它。我已经阅读了很多参考资料(其中提到了可选参数),但在我的案例中没有成功。我怎么能解决这个问题?
我有如下路由器链接:
<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show'}]">
我想传递参数showTour
。但是,当我这样做时,参数是可见的url
,我想隐藏它。我已经阅读了很多参考资料(其中提到了可选参数),但在我的案例中没有成功。我怎么能解决这个问题?
您可以使用历史状态将动态数据传递给您要导航到的组件,而无需将它们添加到 URL 中,如下所示:
this.router.navigateByUrl('/user', { state: { orderId: 1234 } });
或者
<a [routerLink]="/user" [state]="{ orderId: 1234 }">Go to user's detail</a>
你可以这样得到
constructor() {
this.router.events
.pipe(filter(e => e instanceof NavigationStart))
.subscribe((e: NavigationStart) => {
const navigation = this.router.getCurrentNavigation();
this.orderId = navigation.extras.state ? navigation.extras.state.orderId : 0;
});
}
我不确定是否有办法做到这一点,因为数据需要在 URL 字符串中呈现。
我的建议是使用存储所需数据的全球服务。例如:
//some dataService, which store your needed data.
@Injectable()
export class DataService {
_showTour: string;
set showTour(value: string) {
this._showTour = value;
}
get showTour(): string {
return this._showTour;
}
constructor() {}
}
并以这种方式在您的导航组件中使用它:
//your navigation component
@Component({
selector: 'my-app',
template: `
<button class="take-a-tour-btn" (click)="onClick()">
`
})
export class SomeComponent {
constructor(private dataService: DataService, private router: Router) { }
onClick() {
this.dataService.showTour = 'show';
this.router.navigate(['/dashboard']);
}
}
您可以在仪表板组件中使用相同的服务,并通过以下方式获得所需的价值 fe:
//your dashboard component
@Component({
selector: 'my-dashboard',
template: `
<h1>{{ showTour }}</h1>
`
})
export class DashboardComponent implements OnInit {
showTour: string;
constructor(private dataService: DataService) { }
ngOnInit() {
this.showTour = this.dataService.showTour;
}
}
使用状态传递隐藏参数和历史来读取它们。
第一个组件:
this.router.navigate(
[`/dashboard/roles/${id}`],
{ state: { navSettings: navSettings } });
第二部分:
public ngOnInit(): void {
const id = this.activatedRoute.snapshot.params.id;
this.initNavSettings(history.state.navSettings);
}
<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show', skipLocationChange: true}]">
尝试使用 skipLocationChange 属性。
在你的组件中试试这个:(我在 Angular 5.x 中使用它)
this.router.navigate(['/dashboard'], {skipLocationChange: true, replaceUrl: false});
@AddWeb @SailiUnique
您的解决方案有效,但您不必将该属性放在 [routLink] 中。正确的地方在它之外,就像任何财产一样。
像这样:
<div class="row inline rowItem" [routerLink]="['/businessPartnerDetails']" [queryParams]="{ id: bpItem.id, bp: bpItem.companyName}" skipLocationChange=true (click)="onViewDetails(bpItem)">
响应并不完全有效,因为 skipLocationChange 不会更改浏览器 url 上的当前路由,如果您想稍后返回,则从第一个路由支持。
例如,如果您在主页上并使用此:
<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show', skipLocationChange: true}]">Go to dashboard</button>
如果你想从dashboard
tohome
你不能用 object 做到这一点location
,在这种情况下,你需要使用Router
并指定一个确切的路线 ( /dashboard
)。
但这在很多情况下是一个糟糕的解决方案,并且浏览器路由不会从 更改/home
为dashboard
.
不便之处:
dashboard
(当前路线)返回您可以创建数据服务或查看官方角度路由器文档