Angular 2 - Check current active route “name”

后端 未结 6 1611
说谎
说谎 2020-12-24 09:36

I am having an Angular 2 application with several nested children view. But it will be displayed on the same page though several router-outlet.



        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 10:14

    I believe there is an issue with Scott's answer where he uses the ActivatedRoute inside the constructor of the service. This route won't get updated.

    I thought of another solution which might peek your interest. It again comes down on using the data property on the routes, but now using another resolve service:

    You are going to need a RouterConfig like this, where for each route you add the state: StateResolve and a data object containing the state name:

    const routes: RouterConfig = [{
        path: 'queue/:date/:offset/:type',
        component: BundleListComponent,
        resolve: {
           response: BundleListResolve,
           state: StateResolve
        },
        data: {
           state: 'Bundle'
        },
        ...
    ]
    

    don't forget to add the StateResolve service to the providers array

    Your StateResolve service will look something like this:

    @Injectable()
    export class StateResolve implements Resolve {
    
       constructor(private stateService: StateService) {}
    
       resolve(route: ActivatedRouteSnapshot): string {
           let state: string = route.data['state']
           this.stateService.setState(state);
           return state;
       }
    }
    

    Obviously you will need a StateService which has the setState method, but I guess from here it's pretty self-explanatory.

    Perhaps using a resolve guard is a bit eccentric, but if you think about it, you are trying to resolve data before you show the route. In this case, the state inside the data variable, so it does make sense to use the Resolve to access the data property

提交回复
热议问题