Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回到上一个不同页面的返回位置不同查询参数的页面不相同_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 返回到上一个不同页面的返回位置不同查询参数的页面不相同

Javascript 返回到上一个不同页面的返回位置不同查询参数的页面不相同,javascript,angular,typescript,Javascript,Angular,Typescript,为了将状态位置更改回角度中的1步,我们可以使用类似的this.location.back() 当系统不使用重定向到同一个url但使用不同的查询参数时,这种方法可以很好地工作。在这种情况下,step back返回到相同的页面,但使用前面的一组查询参数 我的问题是如何返回到不同的前一页(url),但不返回到具有前一组查询参数的同一页。首先,您必须始终获取前一个url,您可以创建一个服务,在该服务中始终获取当前和前一个url,如下所示: import { Injectable } from '@ang

为了将状态位置更改回角度中的1步,我们可以使用类似的
this.location.back()

当系统不使用重定向到同一个url但使用不同的查询参数时,这种方法可以很好地工作。在这种情况下,step back返回到相同的页面,但使用前面的一组查询参数


我的问题是如何返回到不同的前一页(url),但不返回到具有前一组查询参数的同一页。

首先,您必须始终获取前一个url,您可以创建一个服务,在该服务中始终获取当前和前一个url,如下所示:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';

@Injectable({
 providedIn: 'root'
})

export class RouterService {

 private previousUrl: string = undefined;
 private currentUrl: string = undefined;

 constructor(private router: Router) {
  this.currentUrl = this.router.url;
  router.events.subscribe(event => {
   if (event instanceof NavigationEnd) {
     this.previousUrl = this.currentUrl;
     this.currentUrl = event.url;
   }
  });
 }

 public getPreviousUrl() {
   return this.previousUrl;
 }
}
在您的组件中:

constructor(private routerService: RouterService) {}

navigateBack() {
  this.previousQueryParams = this.routerService.getPreviousUrl().split('?')[1]; // get query params
  const newUrl = `your new url?${previousQueryParams}`;

  // you can create queryParams object here "queryParamsObject"

  this.router.navigate([`${newUrl}`], queryParamsObject)
}

比较没有查询参数的路由最好在服务内部进行,否则在路由中仅更改参数时,服务将返回相同的URL。这是路由服务代码
this.router.events.pipe(filter((x)=>x instanceof NavigationEnd)).subscribe((event:NavigationEnd)=>{const-currentRoute=event.url&&event.url.split('?')[0];if(currentRoute!==this.currentUrl){this.previousUrl=this.currentUrl;this.currentUrl=currentRoute;}     });但您的解决方案的要点是正确的。谢谢