gpt4 book ai didi

angular - 如何将具有某些 id 的路由重定向到人类友好的 url 并处理 Angular 路由中的规范 url?

转载 作者:行者123 更新时间:2023-12-02 10:30:12 27 4
gpt4 key购买 nike

我有两种网址格式

example.com/posts/:postIdexample.com/posts/:postId/:postTitle 就像堆栈溢出单个问题网址一样。

在 Angular 路由中,我需要将所有带有 :postId 的网址重定向到 :postId/:PostTitle 或直接使用 :postId/:PostTitle 加载页面 到达同一页面。

post.module.ts

const routes: Routes = [
{
path: ':postId',
resolve: {data: PdResolver},
redirectTo: ':postId/:PostTitle',
pathMatch: 'full'
},
{
path: ':postId/:PostTitle',
component: PostComponent,
data: {
title: 'This has to be the post fetched title'
}
}
];
  • redirectTo: ':postId/:PostTitle':此处我没有 postTitle,因此会引发错误
  • 如何将 postTitle 附加到网址并避免重复网址问题。
  • 遵循这种模式有哪些最佳实践。

I don't have the title so first I need to get postTitle using the postId, so we have a post data resolver (PdResolver),

问题更新:解决方法:

我尝试使用子组件,它至少解决了这个问题,但仍然想知道这是否是我应该遵循的方法。

    {
path: ':postId',
component: PostOutletComponent,
resolve: {data: PdResolver},
children: [
{
path: ':postTitle',
component: PostComponent,
}]

}

PostOutletComponent 中,我在获取标题后进一步导航到子组件

PostOutletComponent.ts

static stripHtml(html: string) {
let div = document.createElement('DIV');
div.innerHTML = html;
const cleanText = div.innerText;
div = null;
return cleanText;
}

ngOnInit() {
this.reolveData = this._route.snapshot.data;
let postTitle = PostOutletComponent.stripHtml(
this.reolveData.data.data.post_title);
postTitle = postTitle.replace(/\s+/g, '-').toLowerCase();
this.router.navigate([postTitle], {relativeTo: this._route});
}

最佳答案

我根据你的代码做了一个Stackblitz:https://stackblitz.com/edit/angular-r1tvx2

它解决了用户导航到具有现有 ID 但标题错误的 URL 时出现的问题。在上面的示例中,标题已按照 Stack Overflow 的方式进行更正。

我只使用一个解析器和一个组件类来完成它。解析器负责重定向到正确的 URL。请注意,解析器放置在带有标题的更具体的路由中。

路由配置,路由的顺序很重要,首先是更具体的路由,标题为:

  {
path: "posts/:id/:title",
component: PostComponent,
resolve: { somedata: PostDetailResolverService }
},
{
path: "posts/:id",
redirectTo: "posts/:id/title-to-be-repalced",
},
{ path: "**", component: PageNotFoundComponent }
];

解析器,重定向到具有正确标题的 URL:

  resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<Somedata> | Observable<never> {
let id = +route.paramMap.get("id");
let title = route.paramMap.get("title");
return this.getData(id).pipe(
take(1),
mergeMap(res => {
if (res) {
console.log("Resolver - Navigation continues to the route with data:", res);
if (!title || title != res.title) {
this.router.navigate(["posts/" + res.id + "/" + res.title]);
}
return of(res);
} else {
// id not found
console.log("Navigation cancelled");
this.router.navigate([""]);
return EMPTY;
}
})
);
}

关于angular - 如何将具有某些 id 的路由重定向到人类友好的 url 并处理 Angular 路由中的规范 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60484584/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com