在 Angular 7 中导航而不向 URL 添加参数 [英] Navigate in Angular 7 without adding parameter to URL
问题描述
我想在 Angular 7 中的两条路线之间导航,并在它们之间发布数据.但我不想在 URL 中显示这些参数.如何以正确的方式做到这一点?
I want to navigate between two routes in Angular 7 with posting data between them. But I don;t want to show those parameter in URL. How to do it in proper way?
此刻我正在为这样的事情苦苦挣扎:
at this moment I am strugging with something like this:
<代码>this.router.navigate(['/my-new-route', {data1: 'test', test2: 2323, test: 'AAAAAAA'}]);
并将我的网址更改为
<代码>http://localhost:4200/my-new-route;data1=test;test2=2323;test=AAAAAAA
如何从 url 中取消这些数据:
how to do it to cancel those data from url:
<代码>http://localhost:4200/my-new-route
我的情况:
- /form - 以某种形式路由
- /options - 包含一些数据的路由
在/form 路由上 - 用户有一些带有空字段的表单需要手动填写
on /form route - users have some form with empty fields to fill manually
但是在/options 页面上有一些预设配置,当用户选择一个时导航到/form 并且字段会自动填充
but on /options page there is some preset configuration, when user choose one is navigated to /form and fields are fill autmatically
当他们返回另一个页面并再次返回/form 时 - 应该看到空表单.只有从/options 到/form 的链接才能填写这些字段.
when they move back to another page and back again to /form - should see empty form. Only link from /options to /form should fill those fields.
推荐答案
您可以创建一个服务并在两个组件(您要迁移的组件和迁移到的组件)之间共享它.
You can create a service and share it between both the components (the one that you're moving from, and the one that you're moving to).
在服务中声明要传递给 URL 的所有参数,并在 router.navigate([])
之前,设置服务中的参数值.
Declare all the parameters that you want to pass to the URL, in the service, and before the router.navigate([])
, set the values for parameters in the service.
您可以从使用该服务的其他组件访问这些参数.
You can access those parameters from the other component with that service.
示例:
共享服务
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
data1;
test2;
test;
}
组件 1
import { SharedService } from 'location';
import { Router } from '@angular/router';
...
constructor(private _sharedService: SharedService,
private _router: Router) { }
...
this._sharedService.data1 = 'test'
this._sharedService.test2 = 2323;
this._sharedService.test = 'AAAAAAAA';
this._router.navigate(['/my-new-route']);
...
组件 2
import { SharedService } from 'location';
...
private test2;
private test;
private data1;
constructor(private _sharedService: SharedService){ }
ngOnInit() {
this.data1 = this._sharedService.data1;
this.test2 = this._sharedService.test2;
this.test = this._sharedService.test;
...
}
这篇关于在 Angular 7 中导航而不向 URL 添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!