2017-03-01 23 views
2

を構築し、私はRouterModuleを使用しています、私はローカルでテストしていたときにそれが本当にうまく動作角度2つのルートが

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 } 
]; 

私app.module.tsでこれを持っています。/mainMenu/productsはMainComponentに移動し、ProductsComponentを含みます。/Targetingは私をTargetingComponentに連れて行きます。

私はdistの中に生成されたファイルがサーバー上に置かれた

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

Angular 2アプリを作成すると、index.html上でアプリが実行され、ブラウザにどのルートを表示するかが通知されます。だから、これは私が使用している.htaccessのある

をindex.htmlにするために着信トラフィックをリダイレクトするためのhtaccessファイルを追加する必要があります。

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

のために[OK]を動作します。この

<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> 

を使用することができます。 index.htmlと同じディレクトリに配置します。まだ同じ。私は他のステップを逃していますか?それは自動的に.htaccessファイルbtwから読み込むことを知っていますか? – Eddy

+0

あなたはApacheを使用してAllowOverrideを許可する必要がありました – al37350

+0

私はhttp-serverをnpmで使用していますか? – Eddy

0

すべての404エラーに対して「index.htmlを」を返すようにサーバーを設定しますあなたの問題は解決されます。 ASP.NETでは

これは、このようにすることができます:セクションがあるhttp://blog.angular-university.io/angular2-router/ その記事では:

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

私はこの記事はあなたを助けることができると思います「ので、すぐに間違って行くことができますか?」あなたに起こっていることだと思います

+0

リンクには常にコンテキストを提供する必要があります。特に側面が下がった場合。詳細については、[回答]を参照してください。 – MrDarkLynx

0

http-serverng build --aotを使用してビルド時の角度パスではうまく動作しません。代わりに、単純なノードjs expressサーバーを使用することができます。

次のコマンドを使用してexpressをインストールします。

npm install --save express 

server.jsという名前のファイルをルートディレクトリに次の内容で作成します。このようなあなたのpackage.json変更start

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')); 
}); 

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

ng build --aotを使用して構築し、npm startを実行します。

0

あなたはそれが私が上記のファイルを作成し、私