Parent components gets empty Params from ActivatedRoute

前端 未结 5 1422
小鲜肉
小鲜肉 2020-12-08 14:51

I have a main component that has a router-outlet in it. In the component that is loaded in the router-outlet I grab the url parameter like this:

ngOnInit():         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 15:24

    If you'd like to access the router parameters via a service, this approach will not work! consider using a service to prevent the replication of the "Route params value extraction logic" (from this Medium article):

    @Injectable({
      providedIn: 'root'
    })
    export class MyParamsAwareService {
      constructor(private router: Router) { 
        this.router.events
          .pipe(
            filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
            map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
          )
          .subscribe(params => {
          console.log(params);
          // Do whatever you want here!!!!
          });
      }
    }
    

提交回复
热议问题