Angular 2 Activatedroute params not working in Service or outside

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

I have a very strange problem: index.html


4条回答
  •  情书的邮戳
    2021-02-01 04:16

    I have been browsing for a simple solution around the web and finally found something that works in angular 8.

    https://medium.com/@eng.ohadb/how-to-get-route-path-parameters-in-an-angular-service-1965afe1470e

    This works as expected. There are many different flavors available over the web. However only this one worked for me. I am new to rxjs and observer piping so it gets quickly confusing when the chain gets long for me.

    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!!!!
          });
      }
    }
    

    Obviously afterwards you can design your service however you want. To interface your params.

提交回复
热议问题