首页 > 解决方案 > 如何在 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 的情况下显示带有斜杠的相同组件。

标签: angular

解决方案


在您的 app.routes 中,添加到您的路线:

 Routes = [//your routes....
      {path: '/', redirectTo: 'YOUR_HOME_COMPONENT', pathMatch: 'full'},
     ]

那应该可以解决问题。

如果您的文件服务器是例如: http://localhost/site/

确保在构建应用程序时,添加:

ng build --base-href="/site/"


推荐阅读