2017-03-01 85 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> 

它为我工作