在 Angular 中获取路由参数的有效方法

sza*_*kel 10 rxjs typescript angular2-routing angular

如何更有效地使用路由器 Observables?例如,如果我需要加载单个路由参数(假设我们有一个类似的路由/some-resource/:id),我需要订阅路由器事件,然后订阅路由参数以获取值。这需要两次订阅和两次取消订阅。

我想要:

  • 减少样板代码
  • 使代码更具可读性
  • 摆脱订阅

样本

export class SomeComponent implements OnInit, OnDestroy {
  private routerSub: Subscription;
  private routeSub: Subscription;

  someResource: Observable<SomeResourceType>;

  constructor(private someService: SomeService,
              private route: ActivatedRoute,
              private router: Router) {
    this.routerSub = this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.routeSub = this.route.params.subscribe((params) => {
          if (params['id']) {
            this.someResource = this.someService.findById(params['id']);
            // will access the resource using async pipe later
          }
        });
      }
    });
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    this.routerSub.unsubscribe();
    this.routeSub.unsubscribe();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因组件没有被 angular 破坏,但仍然使用不同的路由参数 stackblitz 示例加载,则需要事件订阅来刷新数据:https ://stackblitz.com/edit/angular-router-basic-example- 695kpb

tom*_*een 8

您可以为此使用激活的路由。

constructor(route: ActivatedRoute) {
    this.id$ = route.params
        .pipe(pluck('id'));
}
Run Code Online (Sandbox Code Playgroud)

您可以使用采摘。pluck('id')基本上与map(value => value.id). 如果您不想拥有流而是实际值,您可以这样做并订阅它。但是如果你这样做了,不要忘记取消订阅 observable。您可以使用 take until 运算符来执行此操作。

id;
private _destroyed$ = new Subject<any>();

constructor(route: ActivatedRoute) {
    route.params
        .pipe(
            takeUntil(this._destroyed$),
            pluck('id')
        ).subscribe(id => this.id = id);
}

ngOnDestroy() {
    this._destroyed$.next();
    this._destroyed$.complete();
}
Run Code Online (Sandbox Code Playgroud)


tan*_*ano 7

尝试这个:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    const id = this.route.snapshot.params['id'];
}
Run Code Online (Sandbox Code Playgroud)