我制作此路由配置
@RouteConfig([
{
path:'/profile/:id',name:'Profile',component:ProfileComponent
},
// else
{
path: '/**',
redirectTo: ['Home']
}
])
并使用它来导航带参数{id:5}
的配置文件<a [routerLink]="['Profile', {id:5}]" >Go </a>
我添加到 index.html 负责此基础
<base href="/">
已成功导航至
http://localhost:3000/profile/1
并且运作良好
但是当我在浏览器中粘贴相同的URL手册并点击输入时,它会给我这个错误
因为未从根目录
加载文件而发生错误http://localhost:3000
但浏览器尝试从相对URL目录加载它们
http://localhost:3000/profile/1
更新:我现在使用角度7,这种问题是固定的,无需添加任何东西
答案 0 :(得分:4)
我通过向我的路线添加#
解决了这个问题,例如http://localhost:3000/#/profile/1
,您可以尝试这样做。有人可能会更好地解决这个问题。无论如何,我的解决方案是向HashLocationStrategy
提供商添加AppModule
:
{ provide: LocationStrategy, useClass: HashLocationStrategy }
当然,在此之前,您需要导入LocationStrategy
和HashLocationStrategy
:
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
如果您使用的是RC4或更低版本,请将其添加到bootstrap
方法中,例如:
bootstrap(
AppComponent,
[
{ provide: LocationStrategy, useClass: HashLocationStrategy }
]);
答案 1 :(得分:4)
这很简单。
在地址栏中刷新或手动复制粘贴网址时,您需要 服务器端配置(可能是服务器端路由) 来识别和重定向(使用 PathLocationStrategy )到目的地页面。
角度路由是在客户端,如果你想对工作条件做同样的事情,你需要使用 HashLocationStrategy
答案 2 :(得分:1)
如果使用Express Server。您可以使用另一个称为express-history-api-fallback的中间件软件包。在您的server.js中使用以下代码
import fallback from 'express-history-api-fallback'
import express from 'express'
const app = express()
const root = `${__dirname}/public`
app.use(express.static(root))
app.use(fallback('index.html', { root }))
如果使用的是Webpack服务器。这是webpack服务器配置选项“ historyApiFallback”中的一个选项。根据您的情况将此值设置为true。
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, './client/main.ts'),
target: "web",
output: {
path: path.resolve(__dirname, './comp'),
publicPath: 'http://localhost:8080/',
filename: 'app.bundle.js',
chunkFilename: 'app.bundle.js'
},
devServer: {
port: 8080,
hot: true,
historyApiFallback: true
},
...
}
通过这种方法,您要求浏览器将URL(在浏览器中)存储到缓存中,从而有效地要求服务器回退到index.html