2017-03-01 78 views
2

我使用RouterModule後不工作,我有這個在我的app.module.ts角2路AOT編譯生成

const appRoutes: Routes = [ 
{ path: '', redirectTo: 'mainMenu', pathMatch: 'full' }, 
{ path: 'mainMenu', component: MainComponent, 
    children: [ 
    { 
     path: '', 
     redirectTo: 'products', 
     pathMatch: 'full' 
    }, 
    { 
     path: 'products', 
     component: ProductsComponent 
    } 
    ] 
}, 
{ path: 'targeting', component: TargetingComponent } 
]; 

它的作品真的很好,當我在本地測試。/mainMenu/products將我帶到MainComponent幷包含ProductsComponent。和/ targeting將我帶到TargetingComponent。

我建立

ng build --aot 

在蒸餾水生成的文件放在服務器上的項目。該頁面會自動重定向到/ mainMenu/products。但是,如果我在URL/mainMenu/products或/ targeting中輸入,則不起作用。我得到GET /mainMenu/products" Error (404): "Not found"GET /targeting" Error (404): "Not found"。所以我認爲這是因爲提前編譯而發生的,這是真的嗎?有什麼我應該做的配置這個工作?

我正在使用npm http-server。

回答

3

當您在index.html上構建Angular 2應用程序並告知瀏覽器顯示哪條路線時。所以,你必須添加一個htaccess文件重定向傳入通信的index.html

這是我使用的.htaccess:

RewriteEngine On 
    RewriteBase/
    RewriteRule ^index\.html$ - [L] 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule . /index.html [L] 
+0

好吧,我創建了上述文件。並將其放在與index.html相同的目錄中。還是一樣。我錯過了其他步驟嗎?它如何自動知道從.htaccess文件中讀取btw? – Eddy

+0

你必須使用Apache並允許AllowOverride – al37350

+0

我使用npm http-server,有什麼想法嗎? – Eddy

0

配置您的服務器返回「的index.html」爲所有404錯誤你的問題將得到解決。

在ASP.NET這可能是這樣的:

<customErrors> 
    <error statusCode="404" redirect="~/app/index.html" /> 
</customErrors> 
0

我認爲這篇文章可以幫助你:「可以去錯了,所以很快就什麼」 http://blog.angular-university.io/angular2-router/ 在這篇文章中有一章節我認爲這是發生在你身上的事

+0

您應該始終爲鏈接提供一些上下文。特別是如果一方出現故障。有關更多詳情,請參閱[答案]。 – MrDarkLynx

0

http-server使用ng build --aot構建角度路徑時效果不好。相反,您可以使用簡單的節點js express服務器。

使用以下命令安裝express。

npm install --save express 

在根目錄下創建一個名爲server.js的文件,其中包含以下內容。

const express = require('express'); 
const app = express(); 
const path = require('path'); 

app.use(express.static(__dirname + '/dist')); 
app.listen(process.env.PORT || 8080); 

app.get('/*', function(req, res) { 
    res.sendFile(path.join(__dirname + '/dist/index.html')); 
}); 

在你的package.json更改start這樣子。

"scripts": { 
    "start": "node server.js", 
    //** 
    "postinstall": "ng build --aot -prod" 
}, 

現在建立使用ng build --aotnpm start運行。

0

您可以使用此

<IfModule mod_rewrite.c> 
RewriteEngine On 

# If an existing asset or directory is requested go to it as it is 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d 
RewriteRule^- [L] 
RewriteCond %{HTTPS} off 
RewriteRule (.*) http://%{HTTP_HOST}/sgt/index.html 
</IfModule> 

它爲我工作