Angular 2.0.2: ActivatedRoute is empty in a Service

后端 未结 4 641
孤独总比滥情好
孤独总比滥情好 2020-12-05 17:00

I want to use ActivatedRoute to get route params in a service like I would do in a Component. However, when I inject the ActivatedRoute object in a Service it contains an em

4条回答
  •  失恋的感觉
    2020-12-05 17:47

    The answer of estus provides a good solution when multiple service instances are not an issue.

    The following solution gets a parameter straight from the router and allows the service to have one instance:

    export class Service {
      result: string;
    
      constructor(private router: Router) {
        this.result = router.routerState.snapshot.root.children[0].url[index].path
      }
    }
    

    or as an observable:

    export class Service {
      result: string;
    
      constructor(private router: Router) {
        this.router.routerState.root.children[0].url.map((url) => {
          this.result = url[index].path;
        });
      }
    }
    

    alternatively, when routerState is not available:

    export class Service {
      result: string;
    
      constructor(private router: Router) {
        this.router.parseUrl(this.router.url).root.children.primary.segments[index].toString();
      }
    }
    

    Index is the position of the param in the url.

提交回复
热议问题