简体   繁体   中英

activatedRoute snapshot does not work in TS class constructor

I am facing an issue in typeScript and angular 2. My TS class looks following,

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

@Component({
  selector: 'app-blogdetail',
  templateUrl: './blogdetail.component.html',
  styleUrls: ['./blogdetail.component.css']
})
export class BlogdetailComponent implements OnInit {

   blogId:any;
   title:any;

    constructor(private _activatedRoute:ActivatedRoute) {
    //Does not work
     // this.blogId = this._activatedRoute.snapshot.params['id'];
    //this.title= `This is blog detail for blogID:${this.blogId}`;

   }

  ngOnInit() {
      this.blogId = this._activatedRoute.snapshot.params['id'];
    this.title= `This is blog detail for blogID:${this.blogId}`;
  }

}'

I have to get the rout param in ngOnit event. when I initially use the same code( to get the param) in TS class constructor, I get the blogId variable value as undefined . As far as I understand the sequence of events, they are similar to the below image, ![flow] https://i.stack.imgur.com/41fpe.png

Do we HAVE to get the activatedRoute snapshot values in ngOnIt always ??

You're right. What's happening is that when your component is initiated for your view, your constructor is called. But since that time just the new instance is being created, the route is not activated due to which you don't get the route params. On the other hand, when you're using it in OnInit, the route is activated and you get the params. Still, i would't consider this as the best approach as you should subscribe to the route params in your OnInit to look for the params like :

ngOnInit(){
    this.routeParamsSub = this.route.params.subscribe(routeParams => {
        this.blogId = routeParams['id']; 

       // do something else here
    });
}

Similar approach can be seen in this article .

At the time of object creation angular does not have your params .

So you need to use it on either ngOnInit to assign it to a variable.

Or if you really want this code in constructor then use observable as follows

@Component({...})
class MyComponent {
  constructor(route: ActivatedRoute) {
    const id: Observable<string> = route.params.map(p => p.id);
    const url: Observable<string> = route.url.map(segments => segments.join(''));
    // route.data includes both `data` and `resolve`
    const user = route.data.map(d => d.user);
  }
}

Though use of ActivatedRoute in constructor is not a good practice I belive.

Reference : ActivatedRoute-interface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM