使用routerLink Angular传递不可见或隐藏的参数

时间:2017-10-24 08:11:33

标签: angular router routeparams

我有如下路由器链接:

<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show'}]">

我想传递参数showTour。但是,当我这样做时,参数在url中可见,我想隐藏它。我已经经历了这么多的引用(关于可选参数的说法),但在我的案例中没有成功。我怎么能解决这个问题?

7 个答案:

答案 0 :(得分:9)

我不确定,是否有办法,因为数据需要在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']);
    }
}

您可以在仪表板组件中使用相同的服务,并获得所需的值,例如:这样:

//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;
    }
}

答案 1 :(得分:4)

<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show', skipLocationChange: true}]">

尝试使用skipLocationChange属性。

答案 2 :(得分:2)

在Angular 7中,您可以使用历史状态将动态数据传递到要导航的组件,而无需将其添加到URL中,例如:

this.router.navigateByUrl('/user', { state: { orderId: 1234 } });

<a [routerLink]="/user" [state]="{ orderId: 1234 }">Go to user's detail</a>

您可以通过这种方式获得

const navigation = this.router.getCurrentNavigation();
this.orderId = navigation.extras.state ? navigation.extras.state.orderId : 0;

答案 3 :(得分:1)

使用状态传递隐藏的参数和历史记录以读取'em。

第一部分:

this.router.navigate(
      [`/dashboard/roles/${id}`],
      { state: { navSettings: navSettings } });

第二部分:

public ngOnInit(): void {
    const id = this.activatedRoute.snapshot.params.id;
    this.initNavSettings(history.state.navSettings);
}

答案 4 :(得分:0)

@AddWeb @SailiUnique

您的解决方案有效,但您无需将该属性放在[routLink]中。正确的地方就像任何财产一样。

像这样:

object

答案 5 :(得分:0)

响应不是完全有效,因为skipLocationChange不会更改浏览器url上的当前路由,并且如果您想稍后返回,则从第一个路由返回。

例如,如果您在主页上并使用此功能:

<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show', skipLocationChange: true}]">Go to dashboard</button>

如果您想从dashboard返回到home,则无法使用对象location进行操作,在这种情况下,您需要使用Router并指定一个确切的路线(/dashboard)。

但是在很多情况下,这是一个糟糕的解决方案,并且浏览器的路由不会从/home更改为dashboard

不便之处

  • 浏览器没有刷新到正确的网址
  • 您不能从dashboard(当前路线)返回

您可以创建数据服务或查看官方的angular router docs

答案 6 :(得分:0)

在您的组件中尝试一下:(我正在Angular 5.x中使用它)

this.router.navigate(['/dashboard'], {skipLocationChange: true, replaceUrl: false});