Angular 2.0.2: ActivatedRoute is empty in a Service

后端 未结 4 645
孤独总比滥情好
孤独总比滥情好 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:52

    I came across this issue and the working solution I end with is the following.

    @Component({
      selector: 'app-sample',
      styleUrls: [`../sample.component.scss`],
      templateUrl: './sample.component.html',
    })
    export class AppSampleComponent {
      constructor(private route: ActivatedRoute,
                  private someService: SomeService){}
      public callServiceAndProcessRoute(): void {
        this.someService.processRoute(route);
      }
    }
    
    @Injectable()
    export class SomeService {
      public processRoute(route: ActivatedRoute): void {
      // do stuff with route
      }
    }
    

    So you will pass the ActivatedRoute to the service as a param.

提交回复
热议问题