在Angular 7中导航而不向URL添加参数 [英] Navigate in Angular 7 without adding parameter to URL

查看:101
本文介绍了在Angular 7中导航而不向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'}]);

this.router.navigate(['/my-new-route', {data1: 'test', test2: 2323, test: 'AAAAAAA'}]);

它会将我的网址更改为

http://localhost:4200/my-new-route;data1=test;test2=2323;test=AAAAAAA

http://localhost:4200/my-new-route;data1=test;test2=2323;test=AAAAAAA

如何取消网址中的数据:

how to do it to cancel those data from url:

http://localhost:4200/my-new-route

http://localhost:4200/my-new-route

我的情况:

  1. /form-具有某种形式的路线
  2. /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).

在服务中并在router.navigate([])之前,声明要传递给URL的所有参数,然后在服务中设置参数的值.

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.

示例:

SharedService

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class SharedService {
    data1;
    test2;
    test;
}

Component1

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']);
...

Component2

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆