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

Sai*_*que 18 router routeparams angular

我有如下路由器链接:

<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show'}]">
Run Code Online (Sandbox Code Playgroud)

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

Buz*_*zzy 12

使用状态传递隐藏参数和历史记录以读取它们。

第一个组件:

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

第二个组成部分:

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


Jar*_* K. 10

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

}
Run Code Online (Sandbox Code Playgroud)

并以这种方式在导航组件中使用它:

//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']);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在仪表板组件中使用相同的服务,并以这种方式获得所需的价值:

//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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Fat*_*med 5

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

this.router.navigateByUrl('/user', { state: { orderId: 1234 } });
Run Code Online (Sandbox Code Playgroud)

要么

<a [routerLink]="/user" [state]="{ orderId: 1234 }">Go to user's detail</a>
Run Code Online (Sandbox Code Playgroud)

你可以这样

const navigation = this.router.getCurrentNavigation();
this.orderId = navigation.extras.state ? navigation.extras.state.orderId : 0;
Run Code Online (Sandbox Code Playgroud)

  • @Fateh Mohamed this.router.getCurrentNavigation() 返回 null。 (10认同)

Add*_*Ltd 4

<button class="take-a-tour-btn" [routerLink]="['/dashboard', {'showTour':'show', skipLocationChange: true}]">
Run Code Online (Sandbox Code Playgroud)

尝试使用skipLocationChange属性。

  • 谢谢@AddWeb Solution Pvt Ltd。“参数”仍然出现在您的解决方案中的“url”中。单击该链接时,我的“url”会发生变化。但是,我传递的参数不应出现在“url”中。 (2认同)