2017-07-17 58 views
0

我目前正在開發angular 2應用程序。但我很難理解爲什麼我的路由工作在ng serve而不是在nodemon?我已經嘗試了基於我研究的多種方法,但他們並不像我想象的那樣工作。 (可能是由於我缺乏瞭解)Angular 2路由只適用於ng服務,但不適用於nodemon

方法1

添加在app-routing.module.tsuseHash: true但是,這會導致所有的URL有#出現在它。我在想這是爲了調試目的吧?

const routes = [ 
{ path: '', component: sampleComponent1 }, 
{ path: 'page2', component: sampleComponent2 } 
]; 

@NgModule({ 
    imports: [RouterModule.forRoot(routes, {useHash: true})], 
    exports: [RouterModule] 
}) 

方法2

變化app.js渲染index每當拋出錯誤。此方法在URL中不會有#,但在我的控制檯中將始終返回錯誤,如GET /page2 404 1.688 ms - 987

app.use(function (err, req, res, next) { 
    // set locals, only providing error in development 
    console.log(err.message); 
    res.locals.message = err.message; 
    res.locals.error = req.app.get('env') === 'development' ? err : {}; 

    res.status(err.status || 500); 
    res.render('error'); 
}); 

所以到現在爲止,我堅持更多的方法2作爲URL不顯示在它#,但我不知道,如果方法2是做了正確的道路。有人可以幫我解決這個問題嗎?

+0

'useHash'不僅僅用於調試。這是一個設計選擇。 – HaveSpacesuit

+0

您是否嘗試過構建並使用nodemon服務dist文件夾? – Janpan

+0

@Janpan是的,我會在運行nodemon之前始終做一個構建 – JustStarted

回答

0

這部作品在與角CLI發展的原因是不存在的所有路由都得到擔任的index.html

這使你的角應用程序處理所有的路由不管是什麼URL實際上是要求。一旦您的應用程序在瀏覽器中啓動,Angular路由器(假設您正在使用的)會讀取路由信息並向您的用戶顯示正確的路由。

在這裏還有其他答案解釋這個解決方案以及您的Web服務器。

+0

這聽起來與我在方法2中做的相似嗎?即使我請求一個頁面時,它總會得到一個錯誤404 'localhost/page2'和index.html將得到服務 – JustStarted

+0

B-I-N-G-O !!!是的,所以你的404處理程序是index.html。 – Brocco

相關問題