Home > other >  Getting URL parameter using Observables and passing it to the service
Getting URL parameter using Observables and passing it to the service

Time:04-09

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:

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

How can I fix it in my code?

CodePudding user response:

The 2 subscriptions are asynchronous, and they start executing at the same time. There is no guarantee that the first one will complete before the other one, but you do have mechanisms at your disposal to make sure they execute in the order you want. For example, you could use the switchMap operator to perform the call to the API as soon as the id from your route parameters is available:

GetPostDetails() {
  this.route.params
    .pipe(
      map((param) => param["id"]),
      switchMap((id) => this.FeaturedPostDetail.GetFeaturedPost(id))
    )
    .subscribe((response) => {
      this.featuredPost = response;
    });
}

CodePudding user response:

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;
        })
      } 
   ); 
  }
  • Related