Angular 激活 Route ParamsMap 为空,具体取决于我在提供商中指定服务的位置

Angular Activated Route ParamsMap empty depending on where I specify the service in providers

我正在使用 ActivatedRoute 从注入服务中的路由获取参数。如果我在应用程序模块或应用程序组件中将服务指定为提供者,则参数映射在被调用时为空。如果我将它指定为组件中的提供者,它会提供参数。

为什么会这样。我很难找到有关 ActivatedRoute 的范围以及它如何与服务交互的有用信息。

Link 到 plnkr 中的这种行为。取消注释 a.component.ts 中的第 11 行(提供商字段),当您单击我时可以看到它正在运行! https://plnkr.co/edit/3U9dZm9fdUlG6KW3GyoQ

import {Component, OnInit} from '@angular/core'
import {AService} from './a.service.ts'

@Component({
  selector: 'app-a',
  template: `
    <div>
      <h2>Hello {{id}}</h2>
    </div>
  `,
//  providers: [AService]
})
export class AComponent implements OnInit {
  id: string;

  constructor(private aService: AService) {

  }

  ngOnInit() {
    this.id = this.aService.getId();
  }
}

您看到的行为是由于 ActivatedRoutes 中 paramMap 成员的性质造成的。在您的服务构造函数中,您订阅了 paramMap

constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.paramMap.subscribe(
      params => {
        this.id = params.get('id');
      }
    );
  } 

这会导致其关联组件的路由的 SnapShot 视图。那时,由于您将 a.service.ts 声明为根模块 app.module.ts 的提供者,因此路由的快照将不包含 :id,因为它关联的组件是您的 app.component.ts.因此当你调用你的方法时

getId(): string {
    return this.id;
  }

您正在从您的组件接收与 app.component.ts 相关联的路线的初始 快照 ,并且不包含任何值。

但是,当您将 a.service.ts 声明为组件 a.component.ts 的提供者时,您就创建了 a.service.ts 的新本地实例' 在这种情况下,对 paramMapa.component.ts 关联,并且该组件路由的 快照 确实包含 :id 参数,因此在调用 getid() 时返回给您.

来自Angular source code:

export class ActivatedRoute {
     /** The current snapshot of this route */
       _paramMap: Observable<ParamMap>;
    ...}

>