Resolver example
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable, throwError, timer } from 'rxjs';
import { catchError, delayWhen, retryWhen } from 'rxjs/operators';
import { IPost } from 'src/app/core/interfaces/IPost';
import { PostActionsService } from '../services/post-actions.service';
@Injectable()
export class JobListResolver implements Resolve<IPost[]> {
constructor(private postActionsSvc: PostActionsService) { }
resolve(): Observable<IPost[]> {
return this.postActionsSvc.getLatestPostsRequest()
.pipe(
catchError(err => {
return throwError(err);
}),
retryWhen(errors => errors.pipe(
delayWhen(() => timer(500))
))
);
}
}
Routing module
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { JobListComponent } from './job-list/job-list.component';
import { JobListResolver } from './_resolvers/job-list.resolver';
// Main routes
const routes: Routes = [
{
path: 'jobs/search',
component: JobListComponent,
resolve: { posts: JobListResolver }
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: []
})
export class EmployeePortalRoutingModule {
}
Component
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.getPosts();
this.setSearchForm();
}
// Get all posts from the BD
public getPosts(): void {
this.loader = true;
const posts$ = this.route.data
.pipe(
catchError(err => {
return throwError(err);
}),
shareReplay(),
takeUntil(this.onDestroy$)
);
// Run the subscription
posts$.subscribe(res => {
this.loader = false;
this.posts = res.posts;
// Object destructuring
const [first] = res.posts;
this.post = first;
this.validatePost(first.id, true);
this.validatePost(first.id, false);
});
}
Last updated