Angular 2 获取服务中的routeParams

Angular 2 get routeParams in a service

我想将逻辑从组件转移到服务。但是我发现我在一个服务中获取不到routeParams

我的组件看起来像

import { Component, OnInit }      from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

import { MyService }              from '../services/my.service';

@Component({
  moduleId: module.id,
  templateUrl: 'my.component.html',
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  constructor(private myService: MyService, private route: ActivatedRoute) {;}

  public ngOnInit() {
    this.route.params
      .subscribe((params: Params) => {
        debugger;
        console.log(params);
      });
    this.myService.getParams()
      .subscribe((params: Params) => {
        debugger;
        console.log('Return1:');
        console.log(params);
      }, (params: Params) => {
        debugger;
        console.log('Return2:');
        console.log(params);
      }, () => {
        debugger;
        console.log('Return3:');
    });
  }
};

我的服务看起来像

import { Injectable }                     from '@angular/core';
import { Params, ActivatedRoute }         from '@angular/router';

import { Observable }                     from 'rxjs';

@Injectable()
export class MyService {
  constructor(private route: ActivatedRoute) {;}

  public getParams(): Observable<Params> {       
    this.route.params.subscribe((params: Params) => {
      debugger;
      console.log('Service1:');
      console.log(params);
    }, (params: Params) => {
      debugger;
      console.log('Service2:');
      console.log(params);
    }, () => {
      debugger;
      console.log('Service3:');
    });
    return this.route.params;
  }
};

当我调试时,我可以看到params 在component 中是填充的,而在service 中是空的。这就是结果

Component:
Object {param: "1"}
Service1:
Object {}
Return1:
Object {}

我正在使用 Angular 2.0.0。为什么组件和服务会有所不同?是否可以在服务中获取参数?

编辑: https://github.com/angular/angular/issues/11023

问题是

return this.route.params;

此时路由参数还没有准备好 -> observables -> asynchronicity

我们可以将 ActivatedRoute 从组件传递给服务。然后在服务class

中订阅route.params

根据this你必须向下遍历路由树并从树底部的路由获取数据。

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


    });            
  }
}

我喜欢通过 URL 管理状态,并构建了一个简单的状态服务来观察路由导航结束事件并为每个路由参数公开可观察的端点。

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];
  }
}

然后您可以使用此服务从树中的任何位置观察各个路由参数:

stateService.param('project').subscribe(projectId => {
  console.log('project ' + projectId);
});

在 Angular 8:

中,类似的东西对我有用
export class TheService {

  params$: Observable<any>;

  constructor(private router: Router) {
    this.params$ = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(event => this.getLeafRoute(this.router.routerState.root).snapshot.params)
    );
  }

  private getLeafRoute(route: ActivatedRoute): ActivatedRoute {
    if (route === null) return null; //or throw ?
    while (route.firstChild) route = route.firstChild;
    return route;
  }
}

我使用了@juansb827 答案,当我摆脱事件过滤器并直接遍历该 ActiveRoute 时,我让它开始工作。它对我有用。就我而言,有可能在执行服务时该事件已经发生,因为我的遍历在我的服务中采用了不同的方法。

归功于@juansb827,这是他的回答(使用旧的 RxJS 语法)的更新延续。只需创建一个服务如下:

import { Injectable } from '@angular/core';
import { filter, first } from 'rxjs/operators';
import { ActivatedRoute, NavigationEnd, Params, Router, RouterEvent } from '@angular/router';
import { ReplaySubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class RouteParamsService {
  private routeParamsChangeSource = new ReplaySubject<Params>();
  routeParamsChange$ = this.routeParamsChangeSource.asObservable();

  constructor(private router: Router, private route: ActivatedRoute) {
    this.router.events
      .pipe(filter((event: RouterEvent) => event instanceof NavigationEnd))
      .subscribe(() => {
        let r = this.route;
        while (r.firstChild) r = r.firstChild;
        r.params.pipe(first()).subscribe((params: Params) => {
          this.routeParamsChangeSource.next(params);
        });
      });
  }
}

您现在可以从您应用程序的任何位置(包括其他服务、组件、拦截器等)连接到此服务,如下所示:

constructor(private routeParamsService: RouteParamsService) {
  this.routeParamsService.routeParamsChange$.subscribe((params: Params) => {
    console.log('params', params);
  });
}

只要 URL 发生变化并发出当前参数,它就会触发。 在组件中,您可以将此代码放在 ngOnInit 而不是构造函数中。

根据您的需要,您可能希望使用 Subject 而不是 ReplaySubject。 ReplaySubject 将在您订阅最后一个发出的值后立即触发。 Subject 只会在订阅后触发新的发射。

这应该可以帮助任何想要通过所有子路由递归获取参数的人:

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

@Injectable({
  providedIn: 'root'
})
export class RouterParamsService {
  private routeParamsChangeSource = new BehaviorSubject<Params>({});
  change$ = this.routeParamsChangeSource.asObservable();

  constructor(private router: Router, private activatedRoute: ActivatedRoute) {
    const route$ = this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.activatedRoute)
    );

    const primaryRoute$ = route$.pipe(
      startWith(this.activatedRoute),
      map((route) => {
        let params = {};
        while (route.firstChild) {
          params = {
            ...params,
            ...route.snapshot.params
          };

          route = route.firstChild;
        }
        params = {
          ...params,
          ...route.snapshot.params
        };
        return { route, params };
      }),
      filter((data) => data.route.outlet === 'primary')
    );

    primaryRoute$.subscribe((data) => {
      this.routeParamsChangeSource.next(data.params);
    });
  }
}