Home > Enterprise >  Angular - Variable in the scope is not receiving information after being subscribe it to it
Angular - Variable in the scope is not receiving information after being subscribe it to it

Time:05-27

I have this piece of code that's subscribing from our own service:

Method getVideo()

  getVideo() {
    this.watchService.getVideoByVideoString(this.videoId).subscribe(
      (Response) => {
        this.videoData = Response;
        console.log(Response);
      },
      (err) => console.log(err)
    );
  }

ngOnInit Method

  ngOnInit() {

    this.getVideo();
    console.log(this.videoData);
}

But the variable in case, this.videoData when I console.log on it, it returns as undefined Oo

I know it would be a silly mistake, but can someone help me?

Thanks

CodePudding user response:

The correct syntax is

 getVideo() {
this.watchService.getVideoByVideoString(this.videoId).subscribe(
  (Response) => {
      this.videoData = Response;
      console.log(Response);
      },
  (err) => console.log(err);
);

}

CodePudding user response:

Well i think i would need a little bit of more context, the situation is that if you have console log before the subscription happens and the value gets assigned to the variable you'll always get undefined as the value for this.videoData.

if you only want to see if the value was assigned to the property this.videoData of you class the console.log has to be along side the assignation on the subscription.

note: be aware of any memory leaks caused by not unsubscribing from a observable.

  • Related