2016-12-31 101 views
2

我是Angular 2的新手,我的路由有以下問題。 我的應用使用Auth0進行用戶身份驗證,我的主頁面位於http://localhost:3000/之下,檔案頁面位於http://localhost:3000/profile之下。使用hashtag路由的路由會破壞應用登錄

我有這樣的刷新個人資料頁我當無法得到錯誤404這個錯誤我使用哈希方法

RouterModule.forRoot(appRoutes, { useHash: true })

我的路線解決了,因爲我在這樣一個崗位發現問題:Angular 2 : 404 error occur when i refresh through Browser

我現在的問題是,使用這種散列方法我不能再使用登錄,它會返回一個錯誤。

EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL >Segment: 'access_token' Error: Cannot match any routes. URL Segment: 'access_token' at ApplyRedirects.noMatchError

所以我想知道我該如何解決這個問題。 我的代碼:

app.routing.ts

import {ModuleWithProviders} from '@angular/core'; 
import {Routes, RouterModule} from '@angular/router'; 

import { HomeComponent } from './components/home/home.component'; 
import { ProfileComponent } from './components/profile/profile.component'; 
import { ItemsComponent } from './components/items/items.component'; 

import {AuthGuard} from './auth.guard'; 

const appRoutes: Routes= [ 
{ 
    path:'', 
    component: HomeComponent 

}, 
{ 
    path:'profile', 
    component: ProfileComponent, 
    canActivate: [AuthGuard] 
}, 
{ 
    path:'api/items', 
    component: ItemsComponent, 
    canActivate: [AuthGuard] 
} 

]; 



export const appRoutingProviders: any[] = []; 


export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { useHash: true }); 

的index.html

//I skipped copying links and so on 

    <body> 
    <base href="/"> 
    <my-app>Loading AppComponent ...</my-app> 
    </body> 

app.component.ts

import { Component } from '@angular/core'; 
import {Auth} from './services/auth.service'; 
import {ItemService} from "./services/itemservice/item.service"; 

@Component({ 
    moduleId: module.id, 
    selector: 'my-app', 
    templateUrl: 'app.component.html', 
    providers:[ItemService] 
}) 
export class AppComponent { 
    constructor(private auth:Auth){ 

    } 

} 

app.component.html

//skipped elements 

<nav class="navbar navbar-default "> 
     <div class="container"> 
     <div class="navbar-header"> 
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
     <span class="sr-only">Toggle navigation</span> 
     <span class="icon-bar"></span> 
     <span class="icon-bar"></span> 
     <span class="icon-bar"></span> 
     </button> 
     <a class="navbar-brand" href="#">ngAuth0</a> 
    </div> 
    <div id="navbar" class="collapse navbar-collapse"> 
     <ul class="nav navbar-nav"> 
     <li ><a routerLink="/">Home</a></li> 
     </ul> 
     <ul class="nav navbar-nav navbar-right"> 
     <li ><a href="#" (click)="auth.login()" *ngIf="!auth.authenticated()">Login</a></li> 
     <li ><a routerLink="/profile" *ngIf="auth.authenticated()">Profile</a></li> 
     <li ><a href="#" (click)="auth.logout()" *ngIf="auth.authenticated()">Logout</a></li> 
     </ul> 
    </div><!--/.nav-collapse --> 
    </div> 
</nav> 

auth.service.ts

import { Injectable }  from '@angular/core'; 
import { tokenNotExpired } from 'angular2-jwt'; 

// Avoid name not found warnings 
declare var Auth0Lock: any; 

@Injectable() 
export class Auth { 
    // Configure Auth0 
    lock = new Auth0Lock('7fZnGMP3H3Sl6aTRPQbLWGwPLeHNlm9z', 'myauthID', {}); 


    constructor() { 
    // Add callback for lock `authenticated` event 


    this.lock.on("authenticated", (authResult:any) => { 
    this.lock.getProfile(authResult.idToken, function(error:any, profile:any){ 
     if(error){ 
       throw new Error(error); 
     } 

     localStorage.setItem('id_token', authResult.idToken); 
     localStorage.setItem('profile', JSON.stringify(profile)); //in localStorage only strings can be stored. stringify is needed 

     }); 

    }); 
    } 

    public login() { 
    // Call the show method to display the widget. 
    this.lock.show(); 
    } 

    public authenticated() { 
    // Check if there's an unexpired JWT 
    // This searches for an item in localStorage with key == 'id_token' 
    return tokenNotExpired(); 
    } 
+0

This [answer](http://stackoverflow.com/a/39701248/204699)到一個類似的問題(*如何將HashLocationStrategy與Auth0 Lock小部件一起用於用戶登錄*)可能是有意義的。 –

+0

是的,就是這個問題,我會看看這個。我實際上做的是刪除hashstrategy,現在我用我的服務器這樣管理它,所以刷新總是有效的:app.all('/ *',function(req,res,next){res.sendFile(path。 join(__ dirname,'./client','index.html')); }); – Battalgazi

回答

1

的問題是,當重裝,你實際上是試圖找到你的服務器中的 「個人資料」 的文件(後端)。你實際上希望所有的請求都被angular2(前端)處理。使用hashLocationStrategy,您的個人資料頁面現在處於http://localhost:3000/#/profile

另一個錯誤是,當你有{路徑:「」,..}所以所有的URL匹配的路徑(因爲所有網址都必須在開始「無」),所以你必須使它:

{ 
    path:'', 
    component: HomeComponent, 
    pathMatch: 'full' 
} 

我不知道這是否解決了您的問題,但嘗試此更改,並搜索如何配置您的HashLocationStrategy(在app.module.ts上常見)