Mic*_*jer 9 javascript post routing angular angular7
我想在Angular 7中的两条路线之间导航,并在它们之间发布数据.但我不想在URL中显示这些参数.如何以正确的方式做到这一点?
在这一刻,我正在遭遇这样的事情:
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中取消这些数据:
http://localhost:4200/my-new-route
编辑:
我的情况:
on/form route - 用户有一些带有空字段的表单可以手动填写
但在/ options页面上有一些预设配置,当用户选择一个导航到/表格并且字段自动填充时
当他们移回另一页并再次返回/表格时 - 应该看到空表格.只有/ options到/ form的链接才能填充这些字段.
另一种在不触及查询参数的情况下将信息从一个路由传递到另一个路由的解决方案是通过NavigationExtras的状态字段(从 Angular 7.2+ 开始)
沿着这些思路
// Publish
<a
[routerLink]="['/studies', study.id]"
[state]="{ highlight: true }">
{{study.title}}
</a>
Run Code Online (Sandbox Code Playgroud)
// Subscribe
constructor(private route: ActivatedRoute, ...) {
}
public highlight: boolean;
public ngOnInit() {
...
this.route.paramMap
.pipe(map(() => window.history.state))
.subscribe(state => {
this.highlight = state && state.highlight;
});
...
}
Run Code Online (Sandbox Code Playgroud)
// Alternative
constructor(private router: Router, ...) {
}
public highlight: boolean;
public ngOnInit() {
...
this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
)
.subscribe(state => {
this.highlight = state && state.highlight;
})
...
}
Run Code Online (Sandbox Code Playgroud)
有几种方法可以做到。
尝试 1:
this.router.navigate(['/some-url'], { queryParams: filter, skipLocationChange: true});
Run Code Online (Sandbox Code Playgroud)
尝试 2:
我们可以通过将 EventEmitter 和 BehaviorSubject 与共享服务一起使用来改用此解决方法
在组件 1 中:
this.router.navigate(['url']).then(()=>
this.service.emmiter.emit(data)
)
Run Code Online (Sandbox Code Playgroud)
服务中:
emmiter : EventEmitter = new EventEmitter();
Run Code Online (Sandbox Code Playgroud)
在组件 2 中:内部构造函数
this.service.emmiter.subscribe();
Run Code Online (Sandbox Code Playgroud)
您可以创建一个服务并在两个组件(您要从中移动的组件和要移动到的组件)之间共享它。
在服务中声明要传递给 URL 的所有参数,并在 之前router.navigate([])
为服务中的参数设置值。
您可以从具有该服务的其他组件访问这些参数。
例子:
共享服务
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
data1;
test2;
test;
}
Run Code Online (Sandbox Code Playgroud)
组件 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']);
...
Run Code Online (Sandbox Code Playgroud)
组件 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;
...
}
Run Code Online (Sandbox Code Playgroud)