Angular 2 Activatedroute params not working in Service or outside

后端 未结 4 408
甜味超标
甜味超标 2021-02-01 03:36

I have a very strange problem: index.html


4条回答
  •  走了就别回头了
    2021-02-01 04:39

    Actually, your activatedRoute is correct and updated, but you have all the tree in that. so if you go all the way inside of route.firstChild, you will finally find the last route, which I called deeperActivatedRoute (inside of route.firstChild...route.firstChild)

    So what I did is create a service to track the deeperRoute, and have it always accessible

    import { Injectable } from '@angular/core';
    import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
    
    @Injectable()
    export class ActivatedRouteService {
      private _deeperActivatedRoute: ActivatedRoute;
      get deeperActivatedRoute(): ActivatedRoute {
        return this._deeperActivatedRoute;
      }
    
      constructor(private router: Router, private route: ActivatedRoute) {}
    
      init(): void {
        this.router.events.subscribe(event => {
          if (event instanceof NavigationEnd) {
            // Traverse the active route tree
            let activatedChild = this.route.firstChild;
            if (activatedChild != null) {
              let nextActivatedChild;
              while (nextActivatedChild != null) {
                nextActivatedChild = activatedChild.firstChild;
                if (nextActivatedChild != null) {
                  activatedChild = activatedChild.firstChild;
                }
              }
            }
    
            this._deeperActivatedRoute = activatedChild || this.route;
          }
        });
      }
    }
    

    Then in app.component.ts I start the service (just to ensure it's always tracking)

    export class AppComponent {
      constructor(private activatedRouteService: ActivatedRouteService) {
        this.activatedRouteService.init();
      }
    }
    

    And finally, take your route wherever service you are:

    export class ForbiddenInterceptor implements HttpInterceptor {
      constructor(private activatedRouteService: ActivatedRouteService) { }
    
      doYourStuff(): void {
           //you'll have the correct activatedRoute here
           this.activatedRouteService.deeperActivatedRoute;
      }
    }
    

    Answering the question, you can just take the deeperActivatedRoute and check normally the snapshop.url, just as you would do in a component

提交回复
热议问题