Global variable not being recognized in a function in Angular/JavaScript

I developed a service that retrieves movie information from the omdb API. However, when I attempt to utilize it in my controller and add the result to my movie array, I encounter an issue.

TypeError: Cannot read property 'push' of undefined

.controller('AppCtrl', function(omdbApi) {
    this.movie = [];
    this.getMovie = function(title, year) {
        year = typeof year === 'undefined' ? "" : year;
        omdbApi.getMovie(title, year).then(function(data){
            this.movie.push({
                poster: data.data.Poster,
                title: data.data.Title,
                actors: data.data.Actors,
                plot: data.data.Plot
            });
        });
    }
});

I am seeking clarification as to why I am encountering difficulty pushing to the movie array. I am uncertain if this is an Angular issue or a JavaScript problem. Based on my testing, the received data appears valid. If I simply assign the data to the movie variable, I find myself unable to access it outside of the function.

Answer №1

It's a common error many make. The this object within your .then() callback doesn't point to the same object as the .controller() callback. One solution is to utilize a closure:

.controller('AppCtrl', function(omdbApi) {
    var self = this; // <---- remember this tip
    this.movie = [];
    this.getMovie = function(title, year) {
        year = typeof year === 'undefined' ? "" : year;
        omdbApi.getMovie(title, year).then(function(data){
            self.movie.push({
                poster: data.data.Poster,
                title: data.data.Title,
                actors: data.data.Actors,
                plot: data.data.Plot
            });
        });
    }
});

Alternatively, you can also consider using Function.prototype.bind() to explicitly set a context.

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

Encountering a problem with CRUD operations when attempting to edit and save data from a table using

When attempting to edit the information by clicking the radio button, the details are displayed in the appropriate boxes but the existing data in the table is deleted. My goal is to utilize a single array/scope variable for editing, displaying, and deletin ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

Disregard the views folder when using Express

I've configured a settings file to store important information like the application path and cookie secret for my express app. However, I'm facing an issue where it seems to be disregarding my specified view path directory. config.js: ... expor ...

Leverage Async/Await in React.js with the Axios Library

Recently, I came across an interesting article on Medium titled How to use async/await with axios in react The article discussed making a simple GET request to a server using Async/Await in a React.js App. The server returned a JSON object at /data with t ...

Retrieve the total count of rows present in a specific table

Is there a way to accurately determine the number of rows in a table? I've attempted multiple methods (all unsuccessful) and this is my latest attempt: var _tableOfInterestsCount = wait.Until(x => x.FindElements(By.XPath("//*[@id='gridBody ...

Issue with Typescript and rxjs 6: Property is not found on type 'object'

Currently, I am working on a small application using Ionic 3 to query a Firebase database for two sets of data. Initially, I encountered an error during the first build stating "Property does not exist on type '{}'", however, after saving the .ts ...

Double loading issue with jQuery AJAX

I'm currently working on a website and I've encountered an issue. Below is the jQuery code that I am using: $('input[type="text"][name="appLink"]').keyup(function() { var iTunesURL = $(this).val(); var iTunesAppID = $('i ...

Jest's JavaScript mocking capability allows for effortless mocking of dependent functions

I have developed two JavaScript modules. One module contains a function that generates a random number, while the other module includes a function that selects an element from an array based on this random number. Here is a simplified example: randomNumbe ...

Leverage Express JS to prevent unauthorized requests from the Client Side

Exploring the functionalities of the Express router: const express = require("express"); const router = express.Router(); const DUMMY_PLACES = [ { id: "p1", title: "Empire State Building", description: "One of the most famous sky scrapers i ...

Iterate through an array, mapping the values and then returning a

Look at the code provided: const { aForm, bForm, eForm, qForm, } = this.form; return ( aForm.isEditing || bForm.isEditing || eForm.isEditing || qForm.isEditing ); Can we optimize this in a different ...

Firefox's keyup event

Is it possible to detect a keypress using the jQuery keyup function, as I am facing an issue where it works in Chrome, Edge, IE, and Opera but not in Firefox. $(".textfield").contents().keyup(function(evnt) { document.getElementById("btn_save").style. ...

Exploring the functionality of LINQ for sorting and searching through IEnumerable collections

I am currently new to MVC and LINQ, and I am in the process of learning how to use AngularJs and MVC for a new project that has been assigned to me. To accelerate my learning, I have turned to an online video tutorial. The tutor in the video utilizes a cod ...

When you drag and drop multiple items, the entire data set is erased

I am currently working on a grid that loads data from a JSON file in a React application. When a user holds down the ctrl key on an item, that item is tagged with a new property called selected. My goal is to enable the user to drag and drop the tagged ite ...

Unable to perform 'texImage2D' on 'WebGLRenderingContext'. Encounter an issue when generating canvas texture

My goal is to wrap text around the sleeve of a glTF shirt object, so I created a mesh on top of the sleeve using blender. I then added a canvas texture to the mesh and attempted to render text on it, but unfortunately, I encountered an error: https://i.ss ...

Tips for updating a single attribute in Mongoose

I am currently using mongoose version 4.1.8 and below is an example of my mongo db schema: (function() { 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const DataCodeSchema = new Schema({ ...

The blueimp fileupload feature is failing to activate the progress tracker

My upload script is simple, but it seems to be having issues with triggering the progress. It only triggers the progress method once, and when the file is done uploading, it triggers the complete method and prints done! Chrome 58.0.3029.110 (64-bit) Firefo ...

What is the best way to create a shaking image animation using React Native?

I am trying to create a shaking image animation in React Native when a TouchableOpacity is pressed. So far, I have implemented an animated image with the following code: const backgroundImage = require('./components/images/baby-sleep.jpg') cla ...

Tips on combining JSON array elements into a new JSON array using NodeJS

Is it possible to manipulate a JSON array with 100 objects? Each object contains key values for Job Number, Tax Amount, Line Total, and Line Total plus Tax. The task is to create a new JSON array with Job Number, Total Tax Amount, Sum of Tax Items, and Sum ...

Unable to open fancybox from a skel-layer menu

Seeking assistance with integrating a Fancybox inline content call from a Skel-layer menu (using the theme found at ) <nav id="nav"> <ul> <li><a href="#about1" class="fancybox fancybox.inline button small fit" >about< ...

Unexpected session destruction caused by AJAX call

While this question may seem mundane, please take the time to read through it as I am facing a perplexing issue. The dilemma arises from an AJAX call embedded in one of my pages, specifically a dynamic messaging system: function validateMessage(){ var ...