2017-08-08 70 views
0

我的问题是,当我在浏览器更改URL它总是导致启动路线,当我键入路径相比存在于路由器别的其他的我得到404角路由器不适合浏览器的URL正确响应

APP-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; 
    } 

我有一个登录和公共分量i有这个方法重定向到/如果用户已登录开始

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> 

我用改写配置,所以我跳过#url中

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

,你能否告诉我们的RoutingGuard的代码?也许有一个重定向到/开始/?如果您在路由Guard中调用“isAuthorized”并且您已登录,则当然会将您重定向到/开始/每次。扭转局面,所以你检查!授权 – MeMeMax

+0

@MeMeMax我的问题增加了routingGuard代码! – Hazu

+0

是这样的:“this._mysvc.isAuthorized()”与你的公共组件中的方法相同吗? – MeMeMax

回答

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'; 
+0

我收到此错误信息试图建立“物业‘做’不上键入“可观测存在”,并在如何设置身份验证的值第二种方式? – Hazu

+0

我已经更新了我的答案,如果您使用的是'角cli',您可以添加这些进口到你'polyfills.ts' – PierreDuc

+0

感谢它似乎是现在的工作很好!我想知道为什么我应该在pollyfills.ts中导入这个“import”rxjs/add/operator/do'“?我在routing-gaurd.service.ts中导入它! – Hazu

相关问题