当我在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
}
];
订阅(route
是ActivatedRoute
的实例):
this.route.queryParams.subscribe((params: Params) => {
if (params && Object.keys(params).length > 0) {
const OTHER_NAME = params['OtherName'];
}
});
即使删除通配符路径,它仍然会从URL中删除参数;因此,它永远不会进入上述if
语句中。如何防止查询参数消失?
这可能是一个精确的解决方案,但我找到了一个近似的解决方案。
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, ' '));
}