0

Could you please tell me how to redirect to component when service give error ?In my app I am requesting a service , I want if I got any error some service it will show error component

Here is my code

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

In my current example I am using resolver to get data.

const routes: Routes = [
  {
    path: 'home', 
    component: HelloComponent,
    resolve: { data: TestResolver }

  },
  {
    path: 'error',
    component: ErrorComponent
  },
  {
    path: '', 
    redirectTo: '/home', 
    pathMatch: 'full'
  }
];

I changed requested url so that I will get an error

correct url :https://jsonplaceholder.typicode.com/todos/1 wrong url :https://jsonplaceholder.typicode.com/todoss/1

I want that if I get an error it redirects to Errorcomponent.

@Injectable()
export class TestResolver implements Resolve<Observable<string>> {
  constructor(private testService: TestService) {}

  resolve(): Observable<any> {
    return this.testService.getConfiguration();
  }
}

any update ?

user944513
  • 12,247
  • 49
  • 168
  • 318

2 Answers2

0

You have a couple of options. You could use a Guard to handle this, but because it's based on resolved data, it would probably be a good idea to make it an interceptor. Here's a post that should point you in the right direction re: interceptors Using Router in services in Angular 4

drGrove
  • 166
  • 12
0

You can handle this in your component.ts

Whenever the API call fails just use

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

where you call your service.

Ranjith Eswaran
  • 333
  • 2
  • 12