Angular 2 路由仅在 ng serve 中有效,在 nodemon 中无效
Angular 2 routing only works in ng serve but not nodemon
我目前正在开发 angular 2 应用程序。但是我很难理解为什么我的路由在 ng serve
中工作而不在 nodemon
中工作?我已经根据我的研究尝试了多种方法,但它们并不像我想象的那样有效。 (可能是我理解不够)
方法一
在app-routing.module.ts
中添加useHash: true
但是这会导致所有URL中都出现#
。我认为这是为了调试目的,对吗?
const routes = [
{ path: '', component: sampleComponent1 },
{ path: 'page2', component: sampleComponent2 }
];
@NgModule({
imports: [RouterModule.forRoot(routes, {useHash: true})],
exports: [RouterModule]
})
方法二
更改 app.js
以在抛出错误时呈现 index
。此方法在 URL 中不会有 #
,但在我的控制台中它总是会出现 return 错误,如 GET /page2 404 1.688 ms - 987
。
app.use(function (err, req, res, next) {
// set locals, only providing error in development
console.log(err.message);
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
所以到目前为止,我更多地坚持使用方法 2,因为 URL 中没有显示 #
,但我不确定方法 2 是否是正确的方法做吧。有人可以帮我解决这个问题吗?
这在 Angular CLI 开发中起作用的原因是所有不存在的路由都作为 index.html
这允许您的 Angular 应用程序处理所有路由,而不管 URL 实际请求的是什么。一旦您的应用程序在浏览器中启动,Angular 路由器(假设您正在使用它)将读取路线信息并向您的用户显示正确的路线。
这里还有其他答案也解释了这个解决方案,具体取决于您的网络服务器。
我目前正在开发 angular 2 应用程序。但是我很难理解为什么我的路由在 ng serve
中工作而不在 nodemon
中工作?我已经根据我的研究尝试了多种方法,但它们并不像我想象的那样有效。 (可能是我理解不够)
方法一
在app-routing.module.ts
中添加useHash: true
但是这会导致所有URL中都出现#
。我认为这是为了调试目的,对吗?
const routes = [
{ path: '', component: sampleComponent1 },
{ path: 'page2', component: sampleComponent2 }
];
@NgModule({
imports: [RouterModule.forRoot(routes, {useHash: true})],
exports: [RouterModule]
})
方法二
更改 app.js
以在抛出错误时呈现 index
。此方法在 URL 中不会有 #
,但在我的控制台中它总是会出现 return 错误,如 GET /page2 404 1.688 ms - 987
。
app.use(function (err, req, res, next) {
// set locals, only providing error in development
console.log(err.message);
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
所以到目前为止,我更多地坚持使用方法 2,因为 URL 中没有显示 #
,但我不确定方法 2 是否是正确的方法做吧。有人可以帮我解决这个问题吗?
这在 Angular CLI 开发中起作用的原因是所有不存在的路由都作为 index.html
这允许您的 Angular 应用程序处理所有路由,而不管 URL 实际请求的是什么。一旦您的应用程序在浏览器中启动,Angular 路由器(假设您正在使用它)将读取路线信息并向您的用户显示正确的路线。
这里还有其他答案也解释了这个解决方案,具体取决于您的网络服务器。