logo
down
shadow

Angular.js: Why does array element equal null only when using a factory?


Angular.js: Why does array element equal null only when using a factory?

By : Hui
Date : November 21 2020, 04:03 PM
Hope that helps The problem is that your controller is being instantiated 3 times. Therefore, its constructor is being run 3 times and the data returned from your $http.get is being updated 3 times (since you set up the success handler 3 times). After the first time, it has the values you are wanting; the 2, 3, and 3 are replaced with the respective objects from your elementType list. The problem is that the second and third times the success handler is called, the list is updated again, but ele attribute has already been overwritten. Therefore, it gets updated to undefined because there is no property of the elementType object which matches the key [object Object] (or whatever the string value ends up being). There are a few ways to solve this:
Create a larger factory and push the update to weapon[i].ele into the factory. http://plnkr.co/edit/CSv3ZRSL9K3bOcc9fcMJ Use elementType[weaponStats.ele] in the view, rather than updating the model. http://plnkr.co/edit/UqVz88hVvNATO42A2Aew Update a different attribute (e.g. eleType) instead of overwriting ele. This will prevent you from losing the value loaded from the JSON. (You'll still be updating the objects 3 times.) http://plnkr.co/edit/EqbXUT6gCthtGbC7VQHO
code :


Share : facebook icon twitter icon
Angular Factory returns null

Angular Factory returns null


By : Rajat
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You can't return the database from the function, because the function that receives it is an asynchronous callback.
You can only use the return statement if the entire function is synchronous (e.g. doesn't do any async work, such as reading from files, connecting to databases, network requests, sockets etc).
code :
window.sqlitePlugin.openDatabase({
  name: "myDB.db",
  androidDatabaseImplementation: 2,
  androidLockWorkaround: 1
}, function (db) {
  database = db
  // this happens at some point in the future
});

// this happens straight away
// at this point database is still undefined
return database;
window.sqlitePlugin.openDatabase({
  // ...
}, function (db) {
  database = db
  console.log('A');
});

console.log('B');
return database;
factory.getDatabase = function (callback) {
  window.sqlitePlugin.openDatabase({
    // ...
  }, function (db) {
    // do some stuff with db, when you are ready
    // pass it to the callback, with null as the
    // first argument (because there isn't an error
    callback(null, db);
  });
DatabaseFactory.getDatabase(function(err, db) {
  console.log("intit after database: " + JSON.stringify(database));
});
Angular Factory return null but shows result in console

Angular Factory return null but shows result in console


By : PandaWithAShotgun
Date : March 29 2020, 07:55 AM
Hope that helps I have a factory service and here a method getCount. When I call this method in my controller it's return null but I have tested in my factory service by printing data in the console. It shows data in console but not return any value to my controller. , Return the $db.query.then like so:
code :
obj.getCount = function(table, field) {
    var query = "select count(" + field + ") as total from " + table + "";
    return $db.query(query).then(function(results) {
        if (results.rows.item(0).total) {
            return results.rows.item(0).total;
        } else {
            return 0;
        }
    });
}
DBFactory.getCount('accounts','id').then(function(data) {
    $scope.totalAccount = data;
});
Angular factory function always returns null

Angular factory function always returns null


By : Pablo H
Date : March 29 2020, 07:55 AM
like below fixes the issue The asynchronous call to $http returns a promise, but the function itself returns currentUser, which is null. You need to return the $http promise, if currentUser is null, or return currentUser wrapped in a promise, if it's not null:
code :
angular.module('myWebApp.services')
    .factory('CurrentUserFactory', ['SettingsFactory', '$http', '$q', function(SettingsFactory, $http, $q) {
            var CurrentUserFactory = {};
            var currentUser = null;

            CurrentUserFactory.GetCurrentUser = function() {
                if (!currentUser) {
                    return $http.get(SettingsFactory.myAPIUrl + 'api/users/current', { withCredentials: true }).then(function (response) {
                        currentUser = response.data;
                        return response.data;
                    });
                }
                return $q.resolve(currentUser);
            }

            return CurrentUserFactory;
        }
    ]);
CurrentUserFactory.GetCurrentUser().then(function(currentUser) {
    console.log(currentUser);
});
Use the first and last element (dates) in an array to create an obj.name in an Angular factory/service

Use the first and last element (dates) in an array to create an obj.name in an Angular factory/service


By : Komlan Dossouvi
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I was able to create a solution by doing the following:
I created a method inside my method that creates an array of the dates. I then simply use the first and last element in the array for my period.
code :
function assignWeekNamesAndTotals(arrayOfWeeks) {

    var data = arrayOfWeeks;

    var result = data.reduce(function (p, c, i) {

        var dateArray = [];

        var createDateArray = c.forEach(function (obj) {

            var dateFromObj = Object.keys(obj)[0];

            dateArray.push(dateFromObj);

            return dateArray;
        });

        var total = c.reduce(function (total, obj) {

            for (var k in obj) {
                total += obj[k]; // calculate total
            }
            return total;
        }, 0);

        // Format object in any format you want
        var tmp = {};
        var first = dateArray[0];
        var last = dateArray[dateArray.length - 1]
        tmp.name = "Week: from " + first + " to " + last;
        tmp.total = total;

        p.push(tmp)
        return p;
    }, [])
    console.log("Assign Week names and Totals Output (Step 2: " + JSON.stringify(result, null, "   "));
    return result;
}
[
   {
      "name": "Week: from 2017-01-10 to 2017-01-15",
      "total": 3228
   },
   {
      "name": "Week: from 2017-01-16 to 2017-01-16",
      "total": 363
   }
]
Get element by property in Angular Factory

Get element by property in Angular Factory


By : Rahul Sasidharan
Date : March 29 2020, 07:55 AM
seems to work fine The issue with you code is that forEach is not returning a value (you are not returning the result in findByName method and the return value of forEach is undefined as well), but simply executes a comparison. You can modify you method as following or use filter() method (Works.findByNameUsingFilter example):
code :
angular.module('myApp', [])
.factory('Works', [function(){
    var Works = {};
    Works.projects = [
        {
            name: "ProjectOne",
            string: "stuff1"
        },
        {
            name : "ProjectTwo",
            string : "more stuff",
        },
        {
            name : "ProjectThree",
            string : "stuff",
        }
    ];

    Works.findByName = function(name) {
        var res = '';
        Works.projects.forEach(function(work) {
            if(work.name === name) {
                res = work;
            }
        });    
        return res;
    };
    
    Works.findByNameUsingFilter = function(name) {
        return Works.projects.filter(function(work) {
            return work.name === name;
        });    
    };

    return Works;
}])
.controller("ProjectController", ['$scope', 'Works', function ($scope, Works) {
    $scope.workUsingFindByName = Works.findByName("ProjectOne");
    $scope.workUsingFindByNameUsingFilter = Works.findByNameUsingFilter("ProjectThree");
}]);
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="ProjectController">   
  {{workUsingFindByName.string}}
  <br/>
  {{workUsingFindByNameUsingFilter[0]}}
  </div>
</div>
Related Posts Related Posts :
  • adding a new cell to a table using javascript
  • Orbit controls showing error Uncaught TypeError: Cannot read property 'ROTATE' of undefined
  • Creating a button in Javascript for each value generating in the loop
  • character count of textarea on dynamic character limit length, when click on checkbox in javascript?
  • JavaScript asynchronous function Google Sheet API, data availability is delayed due to being a formula retrieval? How to
  • Store an object in JSON to output in NgxData-Table
  • Wrap unwrapped textNode using regex in arbitrary HTML structure
  • localStorage not working in other host - javascript
  • AngularJS or Javascript: Sort array(ASC & DESC) using index only
  • Onclick change width of dropdown using JavaScript
  • How to center a rotated child div to a rotated parent div and stick to the top of parent div?
  • Make Longest Possible Word Chain with String Array
  • Angular eventemitter not working when emitting the event from directive
  • How to get response while uploading multiple images
  • How to prevent React from posting back when submit button is pressed
  • Need to Auto generate key in Alphanumeric
  • What causes a javascript function to not run it's callback
  • How to convert objects of array in to XML in Javascript
  • Aggregation query using Sequelize and SQLITE
  • Using RNFetchBlob.fs.cp with uri got from react-native-document-picker causeing error
  • Unable to create JavaScript project in Eclipse (IDE for Web and JavaScript Developers)
  • Nodejs - How to route by name in url with express and mongoose?
  • Using the same template file with HtmlWebpackPlugin and EJS?
  • What is the proper regex for string between delimiter with newline
  • How do I show a detailed program in tabulator?
  • how is a value returned from within a caught exception loop?
  • Discord.js How to send only image/photo url in chat
  • Here api won't draw on map using Geojson, can't read property geojson of undefined
  • How to pass data from one html page to another?
  • How to fetch certain quantity of objects from mongoDB with mongoose? (Node.js)
  • Highcharts: create multiple series using JSON data
  • How to add mutiple span to <li> javascript
  • Quality of order
  • Error convert first character to upper case
  • ng-include not loading contents of specified file
  • Demo: how to import this micromodal library
  • How can I access elements that have been created by forEach in Javascript?
  • for loop print same hex color as background color
  • link working on localhost not working on deploy server
  • How to add commas in value
  • Loop through and display content within an object
  • Javascript Regex (alphabet)\n(alphabet)
  • Get reference to arbitrarily (deep) nested node inside JSON/JS object using value of key
  • Runaway raycasting when it should only respond on click
  • Function containing a for loop stops running after click event
  • How To Deploy a Node.js and MongoDB Application on Linux server
  • Why can't update css variable name to apply a different color theme?
  • I use js to dynamically generate some forms but the data cannot be passed to the backend
  • Firebase Realtime Database: Can't send or retrieve data from Firebase Database
  • Puppeteer does not activate button click, despite selecting button
  • In ES6, does Array's find method perform a linear search?
  • Firebase child is not being remove, parent is
  • Does the cocoon gem require n models to be built in the controller new action?
  • I have seen this but not sure what it means
  • Multithreading in JavaScript?
  • How do I formulate my for-loop code to insert values in specific html table cells?
  • calling window.innerHeight upon window resize event doesn't give correct height
  • Adding a time to a Javascript date
  • How to fix these 2 errors in html javascript
  • JS unit testing using enzyme: how to wait for setState within component's method to finish before proceeding with test c
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org