【发布时间】:2020-05-22 15:24:06
【问题描述】:
我正在使用 Angular 8 版本来创建一个新闻应用程序。我需要显示这样的链接:www.domain.com/category/category/title 和 www.domain.com/category。我怎样才能做到这一点?
谢谢
【问题讨论】:
我正在使用 Angular 8 版本来创建一个新闻应用程序。我需要显示这样的链接:www.domain.com/category/category/title 和 www.domain.com/category。我怎样才能做到这一点?
谢谢
【问题讨论】:
您的字面意思是链接文本与其 href like this 不同的链接吗?
如果是这样,
<a [routerLink]="url">{{seoUrl}}</a>
打字稿:
url: 'https://www.google.com';
seoUrl: 'https://www.google.com/category/slug';
或者你想对页面本身的 url 做更多的事情?
编辑:
路由模块
// Declare two routes with an optional title. We will always redirect to the title route. Order matters here - routes will be matched in order.
{ path: 'category/:category/:title', component: CategoryComponent },
// this path declares a route similar to /category/abc where abc is a category
{ path: 'category/:category', component: CategoryComponent }
分类组件
// component decorator omitted for brevity
export class CategoryComponent implements OnInit {
constructor(private route: ActivatedRoute,
private router: Router
) {
}
ngOnInit(): void {
// get the category from the url
const categoryName = this.route.snapshot.paramMap.get('category');
const titleName = this.route.snapshot.paramMap.get('title');
// TODO: implement categoryService
this.categoryService.getCategory(categoryName).subscribe(category => {
if (!title) {
this.router.navigateByUrl(`/category/${category.name}/${category.title}`);
return;
}
// TODO: render the category
});
}
}
【讨论】: