我已經爲我的應用添加了登錄功能。當某人用空白路徑(http://example.com)導航到URL時,我希望HomeComponent顯示哪個將激活AuthGuard,但保留URL路徑爲空。我仍在本地進行測試,所以這可能是問題所在?我不確定。Angular2 - app.module路由:空路徑不會重定向到組件
現在發生了什麼 - 當我導航到本地主機:3000 /我什麼也沒有得到,只是一個空白的屏幕。當我導航到localhost:3000/home時,我的HomeComponent顯示沒有問題,但我希望在URL爲localhost:3000 /時調用HomeComponent。
這是我的app.module文件 - 我不太確定我需要發佈哪些其他文件,因爲問題在於路由。就像我說的,我可以通過輸入路徑來找到所有其他組件。但對於家庭,我不想輸入路徑。
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AlertService } from './login/services/alert.service';
import { AlertComponent } from './directives/alert.component';
import { AuthenticationService } from './login/services/authentication.service';
import { AuthGuard } from './guards/auth.guard';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '**', redirectTo: '', pathMatch: 'full' }
])
],
providers: [
AuthGuard,
AlertService,
AuthenticationService
],
declarations: [
LoginComponent,
AlertComponent,
HomeComponent,
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我自己也嘗試設置這樣我的默認路由,但還是同樣的問題:
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
我的基本href設置爲:
<base href="/" />
我沒有收到任何錯誤,而且我的控制檯看上去很乾淨。再一次,如果我在URL的末尾添加「/ home」,我可以導航,但我需要一個空白的URL路徑以使用AuthGuard顯示HomeComponent。
我已經通過文檔和其他問題,但沒有爲我工作。我不確定我錯過了什麼。任何幫助將不勝感激。讓我知道是否還有其他需要發佈的代碼片段。提前致謝。
可能重複[Angular 2 AuthGuard服務重定向?](https://stackoverflow.com/questions/39002288/angular-2-authguard-service-with-redirect) – 0mpurdy
@joe,你打電話給'{path :'',pathMatch:'full'}'再次在其他地方? 我有同樣的問題,並刪除第二個聲明的路徑解決了我的問題。 – teddybear