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

微笑、不失礼 提交于 2019-12-13 19:17:11

问题


I'm using the ActivatedRoute to get a parameter from my route in an injected service. If I specify the service as a provider in the app module or app component the param map is empty when it gets called. If I specify it as a provider in the component that pulls in the service it has the parameter.

Why is this working this way. I've had trouble finding good information on how the ActivatedRoute is scoped and how it interacts with services.

Link to this behavior in plnkr. Uncomment line 11 (providers field) in a.component.ts to see it working when you click me! 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();
  }
}

回答1:


The behavior you are seeing is due to the nature of the paramMap member in ActivatedRoutes. In your service constructor you subscribe to the paramMap

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

Which results in a SnapShot view of the route for it's associated component. At that point since you declared the a.service.ts as a provider of your root module app.module.ts the snapshot of the route will contain no :id, because the component it is associated with is your app.component.ts. Therefore when you call your method

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

from your component you're receiving the initial snapshot of the route which is associated with app.component.ts and will not contain a value.

However, when you declare a.service.ts as a provider of the component a.component.ts you then have created a new local instance of a.service.ts' In this scenario the subscription made to paramMap is associated with a.component.ts and the snapshot of that components route does contain an :id param and therefore is returned to you when calling getid().

From the Angular source code:

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

>



来源:https://stackoverflow.com/questions/49370474/angular-activated-route-paramsmap-empty-depending-on-where-i-specify-the-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!