我的问题是,当我更改浏览器中的网址时,它总是会指向启动路径,当我输入除路由器中存在的路径以外的其他内容时,我会得到404.
应用-routing.module.ts
const routes: Routes = [
{path: "start", canActivate:[RoutingGuard], component: Start},
{path: "path-1", canActivate:[RoutingGuard], component: One},
{path: "path-2", canActivate:[RoutingGuard], component: Two},
{path: "path-3", canActivate:[RoutingGuard], component: Three},
{path: "path-4", canActivate:[RoutingGuard], component: Four},
{path: "", component: Public},
{path: "**", redirectTo: "", pathMatch:'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
路由-guard.service.ts:
canActivate() {
this._mysvc.isAuthorized().subscribe(data => this.auth = data);
if (!this.auth) {
this._router.navigate(['/']);
}
return this.auth;
}
我有一个登录名,并且在公共组件中我有这个方法,如果用户已登录,则重定向到/ start。
public.component.ts:
isAuthorized(authorized:boolean):void {
if (authorized) {
this._router.navigate(['/start']);
}
}
ngOnInit():void {
this._mysvc.isAuthorized().subscribe(this.isAuthorized.bind(this), this.isAuthorizedError);
}
的index.html:
<html lang="en">
<head>
<base href="/">
<!--<meta charset="UTF-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<app-root></app-root>
</body>
</html>
我使用重写配置,所以我跳过网址中的#
rewrite.config:
RewriteRule /start/? /index.html [NC]
RewriteRule /path-1/? /index.html [NC]
RewriteRule /path-2/? /index.html [NC]
RewriteRule /path-3/? /index.html [NC]
RewriteRule /path-4/? /index.html [NC]
答案 0 :(得分:0)
问题是async
请求您处理为sync
:
canActivate(): Observable<boolean> {
return this._mysvc.isAuthorized().do((auth: boolean) => {
if (!auth) {
this._router.navigate(['/']);
}
});
}
为此,您需要导入do
运算符:
import 'rxjs/add/operator/do'
或者:
async canActivate(): Promise<boolean> {
if (!await this._mysvc.isAuthorized().toPromise()) {
this._router.navigate(['/']);
}
return auth;
}
为此您需要导入toPromise
运算符
import 'rxjs/add/operator/toPromise';