o.o*_*o.o 6 parameters routing angular angular5
当我导航到我的 Angular 应用程序中带有查询参数的页面时,这些参数最终会消失。
例如,如果我去这里:
http://example.com:8080/TestComponent?OtherName=foo
Run Code Online (Sandbox Code Playgroud)
如果将我重新路由到这里:
http://example.com:8080/TestComponent
Run Code Online (Sandbox Code Playgroud)
因此,由于查询参数被删除,我的订阅ActivatedRoute
没有返回任何内容。这是我的路由:
import { Routes } from '@angular/router';
import { TestComponent, PageNotFoundComponent } from './exports/components';
export const ROUTES: Routes = [
{
path: 'TestComponent',
component: TestComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
Run Code Online (Sandbox Code Playgroud)
订阅(route
是 的一个实例ActivatedRoute
):
this.route.queryParams.subscribe((params: Params) => {
if (params && Object.keys(params).length > 0) {
const OTHER_NAME = params['OtherName'];
}
});
Run Code Online (Sandbox Code Playgroud)
即使我删除了通配符路径,它仍然会从 URL 中删除参数;因此,它永远不会包含在上述if
语句中。如何防止查询参数消失?
小智 1
这可以是一个精确的解决方案,但我找到了一个近似的解决方案。
url = localhost:4200/#/test?id=1234
Run Code Online (Sandbox Code Playgroud)
使用 auth-guard-service 和 CanActivate 您的页面。
1.角度路由
{ path: 'test', component: TestComponent, canActivate: [AuthGuardService]}
Run Code Online (Sandbox Code Playgroud)
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, ' '));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3228 次 |
最近记录: |