簡體   English   中英

在編譯構建之后,Angular 2路由無法正常工作

[英]Angular 2 routes not working after aot compilation build

我正在使用RouterModule,我在app.module.ts中有這個

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。 和/ target也將我帶到TargetingComponent。

我使用了這個項目

ng build --aot

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

我正在使用npm http-server。

當您在index.html上構建Angular 2 app時,告訴瀏覽器要顯示哪條路線。 因此,您必須添加htaccess文件以將傳入流量重定向到index.html

這是我正在使用的.htaccess:

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

當使用ng build --aot構建時, http-server對角度路徑不能很好地工作。 相反,您可以使用簡單的節點js express server。

使用以下命令安裝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 --aot並使用npm start運行。

配置您的服務器以返回所有404錯誤的“index.html”,您的問題將得到解決。

在ASP.NET中,這可以是這樣的:

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

我認為這篇文章可以幫到你: http//blog.angular-university.io/angular2-router/在那篇文章中有一節“這么快就會出錯?” 我認為這是你發生的事情

你可以用它

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

這個對我有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM