How we use Angular resolver in different different routing with different api?

Viewed 324

We are trying to use Angular resolve, but we can not understand how to use single resolve interface with different different routing with different api.we have two component ProfileComponent,FormComponent and both component have different api. my code is given below

routing module.ts

const routes: Routes = [
  {
    path: 'form',
    component: FormComponent,
    canActivate: [AuthGuardService],
    resolve: { message: MyresolverService }

  },
  {
    path: 'profile',
    component: ProfileComponent,
    canActivate: [AuthGuardService],
    resolve: { message: MyresolverService }
  },
  {
    path:'pagenotfound',
    component:PagenotfoundComponent
  }

]

myresolver.service.ts

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
@Injectable({
  providedIn: 'root'
})
export class MyresolverService implements Resolve<Observable<string>> {

  constructor(private http:HttpClient) { }

  resolve() {
  return this.http.get('http://dummy.restapiexample.com/api/v1/employees');
}


}
1 Answers

What you're missing is the component part. Here's an example component:

import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html'
})
export class ProfileComponent implements OnInit {
  public name: string;
  public email: string;
  public website: string;
  constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.data.subscribe(response => console.log('here is the resolved data:', response));
  }
}

Obviously it works the same in the form component.

In case you need the parameters in your resolver service, here's an example of that:

export class MyresolverService implements Resolve<Observable<string>> {

  constructor(private http:HttpClient) { }

  resolve(route: ActivatedRouteSnapshot) {
    const userId = route.params['id'];
    return this.http.get(`http://dummy.restapiexample.com/api/v1/employees/${userId}`);
  }
}
Related