Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting URL parameter using Observables and passing it to the service

I’m going to get id parameter from URL and pass it to the service and then, get relevant information from API.

The component is:

export class ShowpostComponent implements OnInit {

  featuredPost: FeaturedPost = {
    id: 0,
    postId: 0,
    subject: '',
    shortDiscription: '',
    discription: '',
    date: '',
    reference: ''
  }

  constructor(
    private FeaturedPostDetail:FeaturedPostService,
    private route:ActivatedRoute
    ) { }

  ngOnInit(): void {
    this.GetPostDetails();
  }
  GetPostDetails(){
    let Id: number;
    this.route.params.subscribe(
      param =>{
        Id = param['id'],
        console.log(Id);
      }
    );
    this.FeaturedPostDetail.GetFeaturedPost(Id).subscribe(
      response =>{
        this.featuredPost = response;
      }
    )
  }
}

My problem is that Id variable in this.FeaturedPostDetail.GetFeaturedPost(Id).subscribe gives error and says:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let Id: number Variable ‘Id’ is used before being assigned. ts(2454)

How can I fix it in my code?

>Solution :

All you need to do is give Id a default value, such as -1 or 0 like so:

GetPostDetails(){
    let Id: number = -1;

Just another note on how the Id is set, because .subscribe is an observable type that is used to emit values over time, I would highly recommend to refactor GetPostDetails into following to make sure the correct value is returned and assigned in time:

GetPostDetails() {
    this.route.params.subscribe(
      param =>{
        const Id = param['id'],
        console.log(Id);
        this.FeaturedPostDetail.GetFeaturedPost(Id).subscribe(
        (response) => {
          this.featuredPost = response;
        })
      } 
   ); 
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading