Angular 2 get routeParams in a service

醉酒当歌 提交于 2019-12-04 06:05:40

We can pass ActivatedRoute to service from component. Then subscribe to route.params in service class

Acording to this you have to traverse down the route tree and get the data from the route at the bottom of the tree.

@Injectable()
export class MyService{

  constructor(private router:Router,private route:ActivatedRoute){   
   this.router.events
    .filter(event => event instanceof NavigationEnd)
     .subscribe((event) => {
         let r=this.route;
         while (r.firstChild) {
            r = r.firstChild
        }
         //we need to use first, or we will end up having
         //an increasing number of subscriptions after each route change.   
         r.params.first().subscribe(params=>{                
           // Now you can use the params to do whatever you want
         });             


    });            
  }
}

the problem is the

return this.route.params;

the route params are not ready at that moment -> observables -> asynchronicity

I like managing state through the URL, and built a simple state service that observes route navigation end events and exposes observable endpoints for each route parameter.

import { Injectable } from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
import {BehaviorSubject} from 'rxjs';
import { filter } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DigStateService {
  public state = {};

  constructor(private router: Router) {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe(() => {
      let route = this.router.routerState.snapshot.root;
      do {
        const params = route.params;
        const keys = Object.keys(params);
        if (keys.length > 0) {
          keys.forEach(key => {
            const val = params[key];
            if (this.state[key]) {
              this.state[key].next(val);
            } else {
              this.state[key] = new BehaviorSubject(val);
            }
          });
        }
        route = route.firstChild;
      } while (route);
    });
  }

  param(key) {
    // if this key does not exist yet create it so its observable when it is set
    if (! this.state[key]) {
      this.state[key] = new BehaviorSubject(null);
    }
    return this.state[key];
  }
}

Then you can use this service to observe individual route params from anywhere in the tree:

stateService.param('project').subscribe(projectId => {
  console.log('project ' + projectId);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!