【问题标题】:Angular 5 Query Parameters DisappearAngular 5 查询参数消失
【发布时间】:2018-05-29 20:57:49
【问题描述】:

当我在 Angular 应用程序中导航到带有查询参数的页面时,这些参数最终会消失。

例如,如果我去这里:

http://example.com:8080/TestComponent?OtherName=foo

如果将我重新路由到这里:

http://example.com:8080/TestComponent

因此,由于查询参数被删除,我对ActivatedRoute 的订阅没有返回任何内容。这是我的路线:

import { Routes } from '@angular/router';
import { TestComponent, PageNotFoundComponent } from './exports/components';

export const ROUTES: Routes = [
    {
        path: 'TestComponent',
        component: TestComponent
    },
    {
        path: '**',
        component: PageNotFoundComponent
    }
];

订阅(routeActivatedRoute 的一个实例):

this.route.queryParams.subscribe((params: Params) => {
    if (params && Object.keys(params).length > 0) {
        const OTHER_NAME = params['OtherName'];
    }
});

即使我删除了通配符路径,它仍然会从 URL 中删除参数;因此,它永远不会进入上述if 语句。如何防止查询参数消失?

【问题讨论】:

  • 如何进行导航?
  • 我只是在地址栏中输入http://example.com:8080/TestComponent?OtherName=foo。然后Routes 数组接管并将我发送到TestComponent html。
  • 问题在this question中讨论。使用routerlinkRouter.navigate 导航时有一些解决方案,但对于初始 URL 或在地址栏中键入 URL 时(据我所知)没有。有一个feature request 允许全局设置保留查询参数。
  • 哇,感谢您提供的信息。 :(
  • 这不是一个更大的问题吗?这似乎是一个相当普遍的问题......我正在经历非常相似的事情。对我来说,我在哈希之前有一个查询,如下所示:example.com/?data=123#/home。当我去这条路线时,查询被删除。非常令人沮丧,我找不到解决方案。我需要查询来跟踪 Google Analytics 广告系列。

标签: angular parameters routing angular5


【解决方案1】:

这可能是一个精确的解决方案,但我找到了一个近似的解决方案。

url = localhost:4200/#/test?id=1234

使用 auth-guard-service 和 CanActivate 您的页面。

1.角度路由

{ path: 'test', component: TestComponent, canActivate: [AuthGuardService]}

2.AuthGuard服务

@Injectable({ providedIn: 'root' })
export class AuthGuardService implements CanActivate {

constructor(private app: ApplicationService) {
    // window.location.href => gives you exact url (localhost:4200/#/test?id=1234).
    // you can parse url like this.

    id = getUrlParameterByName('id', window.location.href);
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   const curPage = route.url[0].path;
   if('test' === curPage) { return true; }
   else {
      // your decision...
   }
}
getUrlParameterByName(name: string, url?: any) {
    if (!url) { url = window.location.href; }
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) { return null; }
    if (!results[2]) { return ''; }
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

【讨论】:

  • 您有 url = localhost:4200/#/test?id=1234 的示例。如果 url 是 localhost:4200/?id=1234#/test/ 怎么办。你将如何进行
  • 我在这里展示了如何在消失之前捕获 url,之后您可以为您的案例自定义 url 解析算法。
猜你喜欢
  • 2019-05-10
  • 2018-07-11
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 2018-07-08
  • 1970-01-01
  • 2018-05-07
相关资源
最近更新 更多