Angular - Scope variable not updating after subscription

Having some trouble with a piece of code that subscribes from our 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);
}

Unfortunately, when I try to access this.videoData, it shows up as undefined. Can someone assist me with this issue?

Thank you.

======

Updated

After running some tests, I found out that I need to manipulate the data within the function itself instead of in the NgOnInit.

The final solution looks like this:

  getVideo() {
    this.watchService.getVideoByVideoString(this.videoId).subscribe(
      (Response) => {
        this.videoData = Response;

        if (this.videoData.title == null) {
          this.titleService.setTitle('InternalVideoChannel');
        } else {
          this.titleService.setTitle('InternalVideoChannel - ' + this.videoData.title);
        }
        if (this.videoData.id == 0) {
          console.log('Video doesnt exist on the database');
          this.router.navigate(['/notFound']);
        }
        console.log(Response);
      },
      (err) => console.log(err)
    );
  }

Thanks!

Answer №1

Here is the accurate syntax:

 fetchClip() {
this.playbackService.fetchClipByClipString(this.clipId).subscribe(
  (result) => {
      this.clipData = result;
      console.log(result);
      },
  (error) => console.log(error);
);

}

Answer №2

It seems like a bit more context is needed in this situation. If you have a console log before the subscription and variable assignment, you'll always receive undefined for this.videoData.

If you specifically want to check if the value was assigned to the property this.videoData of your class, the console.log should be placed right alongside the assignment within the subscription.

Keep in mind the potential memory leaks that can occur from not unsubscribing from an observable.

Edit: As you can see, the console.log is outside the scope of the subscription, resulting in undefined due to the asynchronous nature of an observable subscription.

ngOnInit():void {
   console.log(this.videoData) <- this will be undefined
   this.getVideo(); // <- async 
   console.log(this.videoData) <- this will be undefined
}

The only way to retrieve the value is by console.logging inside the subscription hook like so:

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

The observed issue relates to the behavior of an observable, as it operates similarly to a promise. The console.log runs before the actual assignment takes place, necessitating the need to either bind a function to access the stored value or log within the subscription.

Third edit: If you wish to access the value at a specific point in your application, there isn't a direct solution. However, creating a function that you manually call when needed, perhaps using a timeout or click event, could be a suitable approach.

logVideoDataValue():void {
   console.log(this.videoData) 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining the outcomes of various observables into an object

Suppose you have observables with data structured as shown below: [ { userId: 12, anotherUserId: 23, aField: 'test', anotherField: 'test2' } ] How can I utilize RXJS to fetch the user details for both userIds using this.user ...

Mastering the art of passing and translating languages through selected options in different components using ngx-translate

Currently, I am utilizing the ngx-translate library for localization within a specific component and it is functioning correctly. Here's the setup: I have designed a language selection dropdown component that is being used in the Login component witho ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Verify the username in the registration form before clicking the Register button

I have a PHP-based website and I want to implement a user registration form with unique usernames. How can I validate the username before submitting the request to the database for registration? ...

Setting up environments utilizing restify

Having experience with gulp, I am well-versed in setting up a distinct configuration for each environment within a single configuration file. This allows for running gulp dev to initiate the server using the development environment configuration, gulp stag ...

Utilizing Mongoose promises with Node.js can lead to quicker response times

In my current project using the MERN stack, I have noticed that certain functions in the server-side related to fetching or saving data in MongoDB involve a lot of callbacks. To prevent getting stuck in callback hell, I am exploring a promises-based approa ...

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

How do I modify the date format displayed in the Bootstrap 4 datetimepicker when sending the value?

I have a datetimepicker() set with ID start_date that matches an input name. In the props, the format is specified as YYYY-MM-DD. I want to use this format for my API, but I want the user to see the date displayed in the format DD-MM-YYYY. $('#start_ ...

What specific data am I sending from my ajax request to the MVC controller?

How can I determine the appropriate parameter to use when passing a JavaScript object? Please see below: var all = []; //iterate through each instrument for (var i = 0; i < 3; i++) { var txt = getThis(i);//int var detail =getThat(i);//string ...

Manage the number of choices available on a drop-down selection form

I am working with a PHP variable $a of an integer type. Based on the value assigned to $a, I want certain options to be visible in a form. For example, if $a=1; then only the first two options should be displayed, and if $a=2; then the first three option ...

Guide to transferring information from the scenario file to the function file through regular expressions?

This project utilizes NodeJS, Cucumber, Gherkin, and Selenium. In an attempt to pass a stored value or a URL into the step definitions file using regular expressions, I am encountering some challenges. In my example feature file, I have tried utilizing &a ...

What goes on behind the curtain when moving between components in an Angular and Node.js single-page application (SPA)?

I'm struggling to comprehend how the amalgamation of Angular and Node.js can result in a Single Page Application website. My inquiry will be more comprehensible with an illustration: Let's assume I am attempting to construct a SPA website: On t ...

Is it possible to utilize two nested routes in React Router Dom v6 while using the colon symbol ( : )?

I launched a new react website called My Website Take a look at my website for better understanding In the blog section, I implemented two nested routes <Route path="/blog" element={<Blog />} > <Route path="" e ...

Checking for a timeout in the node spawn process

I have initiated a process that can sometimes run for an extended period of time. Is there a way to set a limit on how long this process can run? For example, is it possible to automatically terminate the process after 3 minutes? ...

Error: The function $(...) that is being called is not recognized as a dialog function

My website has been giving me headaches as I try to integrate a basic CMS. Despite three full days of work, I am still facing one persistent problem! I have exhausted all my known methods, researched some solutions, but none seem to work. In order to iden ...

Which is the Better Choice - Angular 1.4 or 2.0 for Your Next Project?

We are on the verge of beginning a new project using Angular and Kendo Components with the latest version 1.4. However, there is a lot of buzz surrounding Angular 2.0, which lacks backward compatibility. Since there has been no release date announced for ...

Activating list anchor upon click

I have a list that looks like this: <!-- List --> <ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling"> <li class="nav-item"> <a class="nav-link active" id="link1" href="{{ ...

The concept of re-rendering in React functional components

My App component is quite simple export default function App() { const [count, changeCount] = useState(0) const onIncreaseClick = useCallback(() => { changeCount(count + 1) }, [count]) const onPress = useCallback(() => { alert(&apos ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...