当服务出错时如何重定向到错误组件?



你能告诉我如何在服务出错时重定向到组件吗?在我的应用程序中,我正在请求一项服务,我希望如果我遇到任何错误,某些服务将显示错误组件

这是我的代码

https://stackblitz.com/edit/angular-ctwnid?file=src%2Fapp%2Ftest.service.ts

在我当前的示例中,我使用resolver来获取数据。

const routes: Routes = [
{
path: 'home', 
component: HelloComponent,
resolve: { data: TestResolver }
},
{
path: 'error',
component: ErrorComponent
},
{
path: '', 
redirectTo: '/home', 
pathMatch: 'full'
}
];

我更改了requested url,以便出现错误

正确的网址 :https://jsonplaceholder.typicode.com/todos/1错误的网址:https://jsonplaceholder.typicode.com/todoss/1

我希望如果我收到错误,它会重定向到Errorcomponent.

@Injectable()
export class TestResolver implements Resolve<Observable<string>> {
constructor(private testService: TestService) {}
resolve(): Observable<any> {
return this.testService.getConfiguration();
}
}

任何更新 ?

你有几个选择。您可以使用 Guard 来处理此问题,但由于它基于解析的数据,因此将其设置为拦截器可能是个好主意。这是一篇应该为您指出正确方向的帖子:拦截器 在 Angular 4 的服务中使用路由器

你可以在 component.ts 中处理这个问题

每当 API 调用失败时,只需使用

this._service.function().subscribe(success => {
.....
},
error => {
this.router.navigate['error'];
});

您调用服务的位置。

最新更新