我有一个博客,里面有文章。当我在博客页面的特定文章上(url为blogarticle-title),我有一个微调器,并提出一个get请求,当它成功时,我显示与这篇文章相关的信息,但如果我输入url,例如,blog123(我没有这个artilce),我有一个微调器和控制台错误。
app-routing.module
const routes: Routes = [
{
path: '',
loadChildren: () => import('./main-page/main-page.module').then(m => m.MainPageModule),
},
{
path: 'blog',
loadChildren: () => import('./blog-page/blog-page.module').then(m => m.BlogPageModule),
},
{
path: '**',
loadChildren: () => import('./error-page/error-page.module').then(m => m.ErrorPageModule),
},
];
博客-页面路由.模块
export const routes: Route[] = [
{
path: '',
component: BlogPageComponent,
children: [
{
path: '',
component: ArticlesPageComponent,
},
{
path: ':id',
component: ArticlePageComponent,
},
],
},
];
文章页
public ngAfterViewInit(): void {
if (!this.article) {
this.articleSubscription = this.route.paramMap
.pipe(
switchMap(params => {
this.isLoadingInProgress = true;
return this.dataService.getArticleById(params.get('id'));
}),
)
.subscribe(response => {
this.article = response.currentArticle;
this.prevArticle = response.prevArticle;
this.nextArticle = response.nextArticle;
this.navigationModel = {
prevItem: {
route: this.prevArticle ? `blog/${this.prevArticle.id}` : null,
text: this.prevArticle && this.prevArticle.title,
image: this.prevArticle && this.prevArticle.mainImageUrl,
},
nextItem: {
route: this.nextArticle ? `blog/${this.nextArticle.id}` : null,
text: this.nextArticle && this.nextArticle.title,
image: this.nextArticle && this.nextArticle.mainImageUrl,
},
};
this.isLoadingInProgress = false;
this.changeDetection.markForCheck();
},
error => {
this.isLoadingInProgress = false;
});
}
}
已更新: 当url不正确(localhost:4200123)时,会显示错误页面,但使用博客url(localhost:4200blog123)时则无法使用。
一个简单的解决方案是添加一个 error
字段。
error = false;
public ngAfterViewInit(): void {
if (!this.article) {
this.articleSubscription = this.route.paramMap
.pipe(
...
)
.subscribe(response => {
...
this.isLoadingInProgress = false;
this.changeDetection.markForCheck();
},
error => {
this.error = true;
this.isLoadingInProgress = false;
});
}
}
并使用 error
在模板
<div *ngIf="error; else content"><app-error>...</app-error></div>
<ng-template #content>
...
</ng-template>
如果你不想每次都写同样的模板,你可以想到通知系统或覆盖式的提醒信息。
是的,它和预期的一样,因为localhost:4200blog123不是无效的URL路由错误捕捉无效的URL。但是,当你到达文章页面的ngAfterViewInit时,这意味着肯定是一个有效的路由。
解决方法是在视图里面处理无效的动态id,可以用不同的方法。
<div [hidden]="!showError">
<h1>Error Message</h1>
</div>
<div [hidden]="showError">
/ /Articles
</div>