What could cause the variable "this" in a function within an AngularJS service to be undefined?

Why is the inside function undefined in the AngularJS service?

.service('SliceService', function () {
    var self = this;

    var Slice = function(intervals, intervalSpan) {
        self.activeSlice = [];
        self.hasNext = true;
        self.hasPrevious = false;
        self.intervals = intervals;
        self.intervalSpan = intervalSpan;
    }

    Slice.prototype.findIntervalIndex = function (time, slice) {
        slice = slice || self.intervals;
        return _.findIndex(slice, function (o) {
            return o.time === time;
        });
    };

    return Slice;

})

.controller('myController', ['SliceService', function(SliceService) {
    SliceService([arr], 12);
    SliceService.findINtervalIndex(time);
}])

When using it in a controller, the error

TypeError: Cannot set property 'activeSlice' of undefined
occurs.

-

Update

Thank you, everyone! I have made changes to my example to better explain what I am trying to achieve. However, I am now encountering a

TypeError: SliceService.findIntervalIndex is not a function
. Maybe a service is not the best approach for my task?

Answer №1

To ensure the value of "this" is preserved within the anonymous scope, consider saving it in a variable before accessing it:

(function(){
    'use strict';

    angular.module('myServices').service('SliceService', function () {
        var context = this;

        var Slice = function(intervals, intervalSpan) {
            context.activeSlice = [];
            context.hasNext = true;
            context.hasPrevious = false;
            context.intervals = intervals;
            context.intervalSpan = intervalSpan;
        }

        return Slice;
    });
}());

Using Bind:

    angular.module('myServices').service('SliceService', function () {
        var Slice = function(intervals, intervalSpan) {
            this.activeSlice = [];
            this.hasNext = true;
            this.hasPrevious = false;
            this.intervals = intervals;
            this.intervalSpan = intervalSpan;
        }.bind(this);

        return Slice;
    });

Note: using arrow function of javascript ES6 makes sure that this always points to the same context. so you could replace regular function with arrow function. This is however not universally supported without transpiling.

service('SliceService', ()=>{ 
 // operations
}

Answer №2

Big shoutout to @SeedyROM and some helpful Google searches on angular services. With their assistance, I was able to resolve all the issues I was facing...

angular.module('vpower.services').service('SliceService', function () {
    this.activeSlice = [];
    this.hasNext = true;
    this.hasPrevious = false;
    this.intervals = [];
    this.intervalSpan = 12;

    this.findIntervalIndex = function (time, slice) {
        var curTime;
        slice = slice || this.intervals;
        return _.findIndex(slice, function (o) {
                curTime = o.time._i || o.time;
            return curTime === time;
        });
    };

It became clear to me that I had some misconceptions about how services operate.

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

Enhance the performance of node.js when processing data from a massive file

My dilemma lies in the challenge of reading and processing a large file with numerous rows. When dealing with small files under 50kb, everything runs smoothly. However, I am faced with a 15MB file for a programming competition, which serves as a hard input ...

Exporting modules in Node.js allows you to use functions

Can you explain why this code snippet is successful: exports.foo = 'foo'; var bar = require('./foo'); console.log(bar); // {foo: 'foo'} While this one fails to produce the desired output: var data = { foo: 'foo' ...

`The importance of module communication in AngularJS`

Is it feasible to have multiple angular-modules linked to various sections within a single shell page? And if so, is there a way for these modules in AngularJS to communicate with each other? ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

The resolvers contain the Query.Mutation but it is not specified in the schema

const { ApolloServer, gql } = require('apollo-server-express'); const express = require('express'); const port = process.env.PORT || 4000; const notes = [ { id: '1', content: 'This is a note', author: 'Adam ...

What steps should be taken to resolve the update problem in Sequelize?

Having an issue with the update method in MySQL ORM. User.update({ ResetPasswordToken : resetPasswordToken },{ where: { UserName: 'testuser' } }) Receive this Sequelize Log: Running query: UPDATE Users SET ResetPasswordToken=?,updat ...

Angular Multi-element slider

I am having some trouble getting the angular carousel to work. As a beginner in angular, I am struggling to get the ng-repeat directive to function correctly. Here is what I have tried: <div id="slides_control"> <div> <carousel interval ...

Unable to access URLs manually

Each time I try to enter a url manually into my browser for an Angular-based website, I always encounter the following error: 'HTTP 404 The resource cannot be found Requested URL: /register' The only functional url is http://localhost:XXXX/in ...

The functionality of $viewContentLoading appears to be malfunctioning

Before the content is loaded, I'm attempting to log a value. I am using $viewContentLoading within the init function, but the value is not being logged. Can anyone help me identify the issue with my code? var app = angular.module('plunker&apos ...

The Controller is encountering an empty child array when attempting to JSON.stringify it

After examining numerous similar questions, I am uncertain about what sets my configuration apart. I've experimented with various ajax data variations and JSON formatting methods, but the current approach seems to be the closest match. This issue is ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

Unpacking nested objects using dynamically generated property names in a React state - a guide

Having trouble with using setState and figuring out how to destructure the object with a dynamic property name, denoted by id. The state looks like this after computation: { "inputConfig": { "5d4d684cadf8750f7077c739": { "0": "5d4d ...

Tips for creating ui-sref links by using a mix of translate and ng-bind-html

I'm having trouble figuring out how to create a functional ui-sref link from a translated string. Using angular 1.4.9 along with angular translate 2.9.0 Below is the relevant code snippet <div ng-bind-html="$scope.getTranslatedText(someObject)"& ...

Updating a particular column in a table with Jquery

In this table : $('#listview-table tr').each(function() { var status_id = $(this).find(".listViewEntryValue").$('[data-name~="cf_1525"]').text(); alert(status_id); }); <table id="listview-table" class="table listv ...

What are the benefits of having a service dedicated to interacting with a single entity, while another service is responsible for handling a group of entities?

Imagine we have a User entity. Would it be better to have two smaller services (User and Users) or one larger service that manages both individual Users and collections of Users? If it's the latter, what's the recommended practice for naming the ...

How to apply props conditionally in VueJS?

I have a component called blogPost (Component A) that is imported in another component named B. When a button in Component B is clicked, Component A opens in a modal. There are two different use cases for this scenario. 1. One case requires passing 2 prop ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...