angular - 如何在 Angular 7 中的 URL 中添加尾部斜杠,而不会在刷新时出现 404 问题?
问题描述
我在 Angular 7 的 url 末尾添加斜杠,下面是我发现在 Angular 中添加斜杠的代码,它工作正常。但是当我刷新页面时,它会将我重定向到 404 组件。
import {Location, PathLocationStrategy} from '@angular/common';
const _orig_prepareExternalUrl =
PathLocationStrategy.prototype.prepareExternalUrl;
PathLocationStrategy.prototype.prepareExternalUrl = function(internal) {
const url = _orig_prepareExternalUrl.call(this, internal);
if (url === '') {
return url;
}
console.log('For ' + internal + ' we generated ' + url);
if (url.endsWith('.html')) {
return url;
}
if (url.endsWith('/')) {
return url;
}
return url + '/';
};
Location.stripTrailingSlash = function (url) {
const /** @type {?} */ match = url.match(/#|\?|$/);
const /** @type {?} */ pathEndIdx = match && match.index || url.length;
const /** @type {?} */ droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
const first = url.slice(0, droppedSlashIdx);
const last = url.slice(pathEndIdx);
if (first.endsWith('.html')) {
return first + last;
}
return first + '/' + last;
};
我希望在没有 404 的情况下显示带有斜杠的相同组件。
解决方案
在您的 app.routes 中,添加到您的路线:
Routes = [//your routes....
{path: '/', redirectTo: 'YOUR_HOME_COMPONENT', pathMatch: 'full'},
]
那应该可以解决问题。
如果您的文件服务器是例如: http://localhost/site/
确保在构建应用程序时,添加:
ng build --base-href="/site/"
推荐阅读
- spring-boot - Spring Data JPA 垃圾回收
- c# - 字符串值在类中保持不变,但在外面是正确的?
- node.js - 节点js POST请求错误错误[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头
- python - 加入两个具有相同值和不同键的字典列表
- html - 如何制作溢出-y:滚动占边框大小
- python-3.x - Is there any way to add scroll bar in 'markdown' cell to shorten jupyter notebook?
- c# - 调用 Web 服务的 C# DLL COM 在 Excel VB 中不起作用
- ios - SWIFT:将 UITableViewCell 连接到两个不同的详细视图控制器
- python - 随机化数组值
- android - Android模拟器ISO?