Angular Api Router Resolve



1. Create Services file and make fetching function.
public getMemberInfo(data: any = {}) {
let url = "sp/auth/get-member-info";
return this.post(url, data);
}

2. Create Resolve
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AuthService } from './../../services/auth.service';

@Injectable()
export class ProfileResolver implements Resolve<Observable<any>> {
  constructor(private authApi: AuthService) {}

  resolve(): Observable<any> {
return this.authApi.getMemberInfo();
  }
}

3. import Modules file.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { ProfileComponent } from './components/profile/profile.component';
import { ProfileResolver } from './components/profile/profile.resolver';

@NgModule({
  declarations: [ProfileComponent],
  imports: [
CommonModule,
HttpClientModule,
AuthRoutingModule,
ReactiveFormsModule
  ],
  providers: [ProfileResolver]
})
export class AuthModule { }

4. Import resolve in Router modules.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProfileComponent } from './components/profile/profile.component';
import { ProfileResolver } from './components/profile/profile.resolver';

const routes: Routes = [
  { path: 'profile', component: ProfileComponent, resolve: { users: ProfileResolver }, pathMatch: 'prefix' },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthRoutingModule { }

5. Import your compoenets.

export class ProfileComponent implements OnInit, AfterViewInit {
  public profile: any;

  constructor(public authApi: AuthService, public router: Router, public route: ActivatedRoute) { }
 
  ngOnInit(): void {
this.profile = this.route.snapshot.data.users.data;
  }
}

6. view page 
{{profile | json}]

Source: https://angular.io/api/router/Resolve
Demo: https://stackblitz.com/edit/angular-route-resolvers
Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment