如何在刷新时在没有404问题的情况下在angular 7中的URL中添加尾部斜杠?

时间:2019-01-16 20:23:22

标签: angular

我在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的带有斜杠的相同组件。

2 个答案:

答案 0 :(得分:1)

在您的app.routes处,添加到您的Routes中:

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

应该可以解决问题。

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

请确保在构建应用程序时添加以下内容:

  

ng build --base-href =“ / site /”

答案 1 :(得分:1)

以下代码对我有用:

export const contactUsRoutes: Routes = [
    {
        path: 'contact-us/.', component: ContactUsComponent
    }
];

<a [routerLink]="['/contact-us/.']">Contact us</a>

并在main.ts中添加以下代码:

import { Location } from '@angular/common';

const __stripTrailingSlash = (Location as any).stripTrailingSlash;
(Location as any).stripTrailingSlash = function _stripTrailingSlash(url: string): string {
  const queryString$ = url.match(/([^?]*)?(.*)/);
  if (queryString$[2].length > 0) {
    return /[^\/]\/$/.test(queryString$[1]) ? queryString$[1] + '.' + queryString$[2] : __stripTrailingSlash(url);
  }
  return /[^\/]\/$/.test(url) ? url + '.' : __stripTrailingSlash(url);
};

我已通过以下链接获得此解决方案:

https://stackblitz.com/github/ssatz/Angular5-Preserve-Trailing-Slash