Angular-routerLink和状态问题 [英] Angular - Issue with routerLink and state
问题描述
我想从HTML页面使用routerLink和state路由到另一页面.使用标签没有问题,在登录页面的ngOnInit期间,我可以按预期检索状态.使用标签主页也可以导航,但是状态结果未定义.
From an html page I want to route to another page using routerLink and state. With tag there's no issues, during ngOnInit in landing page, I can retrieve state as expected. Using tag home page is navigate as well but state results undefined.
我怎么了?
登录页面的HTML
<button routerLink="/home" [state]="navExtra.state">
Go Home Page via button
</button>
<a routerLink="/home" [state]="navExtra.state">Go Home Page via a</a>
登录页面的数量
import { Component, OnInit } from '@angular/core';
import { NavigationExtras } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss']
})
export class LoginPage implements OnInit {
navExtra: NavigationExtras = {
state: { data: { a: 'a', b: 'b' } }
};
constructor() {}
ngOnInit() {}
}
首页
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss']
})
export class HomePage implements OnInit {
constructor(
private router: Router
) {}
ngOnInit() {
console.log(this.router.getCurrentNavigation().extras.state);
}
}
推荐答案
我认为无法通过按钮传递 state
.如果我们检查 routerLink
的源代码,我们可以看到...
I don't think it is possible to pass state
through a button. If we inspect the source code of routerLink
, we can see...
不是一个 a
标记时:
@Directive({selector: ':not(a):not(area)[routerLink]'})
状态
不包含在 extras
中:
@HostListener('click')
onClick(): boolean {
const extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
而当我们有一个 a
标记时:
whereas when we have an a
tag:
@Directive({selector: 'a[routerLink],area[routerLink]'})
其中包括:
@HostListener('click', [/** .... **/])
onClick(/** .... **/): boolean {
// .....
const extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
state: this.state // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< here!
};
this.router.navigateByUrl(this.urlTree, extras);
return false;
}
因此,您的选择是将链接的样式设置为看起来像按钮,或者在按钮单击时调用一个函数来执行导航,如其他答案所示,在这里,我指的是 AbolfazlR :
So your option is to style that link to look like a button, or then call a function on button click which performs the navigation, like presented in other answer, here I kindly refer to that code posted by AbolfazlR:
this.router.navigate(['home'], this.navExtra);
这篇关于Angular-routerLink和状态问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!