Using Resolve In Angular2 Routes

前端 未结 5 882
盖世英雄少女心
盖世英雄少女心 2020-11-27 15:05

In Angular 1 my config looks like this:

$routeProvider
  .when(\"/news\", {
    templateUrl: \"newsView.html\",
    controller: \"newsController\",
    resol         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 15:56

    You can create your Resolver in Angular2+ and apply it to the router quite easily. look at the below, here is the way to create the Resolver in Angular:

    @Injectable()
    export class AboutResolver implements Resolve {
    
      constructor(private aboutService: AboutService, private router: Router) {}
    
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
        const id = route.params['id'];
        return this.aboutService.getById(id);
      }
    }
    

    then in the router config:

    export const Routes: RouterConfig = [
      { path: 'about',  component: AboutComponent, resolve: { data: AboutResolver } }
    ]; 
    

    and finally in your component:

    ngOnInit() {
      this.route.data.subscribe((data: { about: About }) => {
        this.about = data.about;
      });
    }
    

提交回复
热议问题