Get dynamic data from route with resolve in Angular 4

Get dynamic data from route with resolve in Angular 4

Create server resolver service

–server-resolver.service.ts

import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { Injectable } from "@angular/core";
import { ServersService } from "app/servers/servers.service";

interface Server {
    id:number;
    name:string;
    status:string;
}

@Injectable()
export class ServerResolver implements Resolve {
    constructor(private serversService: ServersService) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | Server {
        return this.serversService.getServer(+route.params['id']);
    }
}

–server.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router, Data } from "@angular/router";

@Component({
  selector: 'app-server',
  templateUrl: './server.component.html',
  styleUrls: ['./server.component.css']
})
export class ServerComponent implements OnInit {
  server: {id: number, name: string, status: string};

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.data
      .subscribe(
        (data: Data) => {
          this.server = data['server']
        }
      )
  }

}

–app-routing.module.ts

const appRoutes: Routes = [
    { path: '', redirectTo:'/home', pathMatch:'full'},
    { path: 'home', component: HomeComponent},
    { path: 'users', component: UsersComponent, children: [
      { path: ':id/:name', component: UserComponent},
    ]},
    { path: 'servers', canActivateChild:[AuthGuard], component: ServersComponent, children: [
      { path: ':id', component: ServerComponent, resolve: {server: ServerResolver}},
      { path: ':id/edit', component: EditServerComponent, canDeactivate: [CanDeactivateGuard]},
    ]},
    { path: 'error-404', component: ErrorPageComponent, data: {message: 'Page not found!'}},
    { path: '**', redirectTo: '/error-404'}
  ]

Leave a Reply

Your email address will not be published. Required fields are marked *