2017-01-08 46 views
0

我已經在網上搜索瞭解如何在手動輸入url(或頁面刷新)時如何導航到Angular2中的特定組件。我找不到任何東西,除了beta2 angular2的實施幾乎2歲(Such as here)。我有一個簡單的使用node/express的角度web應用程序。獲得客戶端導航工作正常,但讓客戶端處理服務器請求我不知道這是如何工作,甚至如何實現。任何人都可以幫忙Angular2服務器url導航

我只是簡單地做: http://localhost:3000/login - 這適用於在應用程序中導航,但是當我刷新它不起作用。我想如果簡單地實現這一點,將會有大量的資源,但是我沒有找到基本的東西。謝謝!

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 
import { LocationStrategy, HashLocationStrategy } from '@angular/common'; 
import { AppModule } from './app.module'; 

platformBrowserDynamic().bootstrapModule(AppModule); 

app.module.ts:

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { RouterModule } from '@angular/router'; 

import { AppComponent } from './components/app.component'; 

import { LoginComponent } from './components/auth/login'; 
import { IndexComponent } from './components/home/index'; 

import { PageNotFoundComponent } from './components/not-found.component'; 


@NgModule({ 
    imports:  [ BrowserModule, 
    RouterModule.forRoot([ 
    { 
    path: 'login', 
    component: LoginComponent 
    }, 
    { 
    path: '', 
    component: IndexComponent 
    }, 
    { path: '**', component: PageNotFoundComponent } 
])], 
    declarations: [ AppComponent,IndexComponent,LoginComponent,PageNotFoundComponent ], 
    providers: [ ], 
    bootstrap: [ AppComponent ] 
}) 

export class AppModule { } 

回答

1

將是非常高興看到您的服務器的路由器定義。

在瀏覽應用,但是當我刷新它不

你說什麼工作的時候也能正常工作?您的服務器是否回覆404狀態碼?

如果是這樣,這裏發生的事情:

  • 瞭解它們在localhost:3000:您的瀏覽器做一個GET請求/和index.html的返回給客戶端。
  • 然後角開始和實例化您的默認組件,IndexComponent
  • 然後,單擊指向本地主機鏈接:3000 /登錄
  • 在這裏,沒有要求被到您的服務器,角度剛剛實例化正確的組件:LoginComponent
  • 如果刷新,您的瀏覽器會在localhost:3000/login上發出GET請求,這會給您一個404,因爲此路由不存在。

解決您的問題,使用通配符,以滿足您的文件:

app.get('*', (req, res) => { 
    res.status(200).sendFile(indexFile); 
}); 
0

你必須讓所有的請求返回查看包含根Angular2應用標籤。那麼不管你的URL是什麼,它都會加載相同的視圖,並且它會讓Angular2處理路由。

How to handle angular2 route path in Nodejs

0

您是否嘗試過把你的index.html<header>部分是這樣的:

<base href="/"> 

或有時它也需要:

<base href="/index.html">