角度5查询参数消失

时间:2018-05-29 20:57:50

标签: angular parameters routing angular5

当我在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声明。如何防止查询参数消失?

1 个答案:

答案 0 :(得分:1)

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

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

使用auth-guard-service并可以激活您的页面。

1。角路由

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

2.AuthGuardService

@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, ' '));
}