CanActivate and Resolver - quan1997ap/angular-app-note GitHub Wiki
CanActivate is a router guard that is executed to check if the router should navigate to the route and the Resolver is a data provider, that fetch data for the component before the router starts navigation. So, because you are trying to fetch data, you should use a Resolver and not a Guard.
import { AuthService } from './../services/auth.service';
import { Injectable } from '@angular/core';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
} from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authService.currentUserValue;
if (currentUser) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.authService.logout();
return false;
}
}
{
path: 'customer-management',
canActivate: [AuthGuard] ,
loadChildren: () =>
import('../modules/customer/customer.module').then((m) => m.CustomerModule),
},
user-resolver.service.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserResolverService implements Resolve<any> {
constructor(private http: HttpClient) { }
/**
* resolve method
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot): Observable<any> {
const userId = route.params['id'];
const url = `https://jsonplaceholder.typicode.com/users/${userId}`;
return this.http.get(url);
}
}
app.module.ts
import { UserResolverService } from './user-resolver.service';
const ROUTES: Routes = [
{
path: 'users/:id',
component: UserComponent,
resolve: {
user: UserResolverService
}
}
];
@NgModule({
providers: [UserResolverService]
})
export class AppModule { }
user.component.ts
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
templateUrl: './user.component.html'
})
export class UserComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.data.subscribe(
response => {
console.log(response.use)
}
);
}
}