2017-08-08 58 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

相關問題