如何在角度7中的URL中添加尾部斜杠而在刷新时没有404问题? [英] How to add trailing slash in URL in angular 7 without 404 issue on refresh?

查看:49
本文介绍了如何在角度7中的URL中添加尾部斜杠而在刷新时没有404问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 7的url末尾添加了斜杠,下面是我发现在angular及其末尾添加斜杠的代码.但是,当我刷新页面时,它会将我重定向到404组件.

I am adding trailing slash in url end in Angular 7, below is the code i found to add trailing slash in angular and its working fine. But when i refresh page it redirect me to 404 component.

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

I expect to show same component on which i am with trailing slash without 404.

推荐答案

以下代码为我工作::

Below code worked for me::

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

.

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

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

And add below code in your 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);
};

我已经在下面的链接中找到了此解决方案:

I have referred below link for this solution:

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

这篇关于如何在角度7中的URL中添加尾部斜杠而在刷新时没有404问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆