AngularJS API can be utilized to retrieve an object

Working with the Riot game API involves creating a factory and utilizing it to retrieve and organize data.


        angular.module('starter.services', [])

    .factory('API',function($http){
    var data={};
    var token = "****";
    return{
        Getalldata : function(name){


            $http.get("https://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/" + name, {
          params: {
            api_key: token
          }
        })
        .success(function(response, error) {

          var dbc = [];
          //console.log(response);
          res = response[name];
          //console.log(res);
          id = res.id;

          //$scope.img = "http://sk2.op.gg/images/profile_icons/profileIcon"+res.profileIconId+".jpg";
          
          $http.get("https://eune.api.pvp.net/api/lol/eune/v1.3/stats/by-summoner/" + res.id + "/summary", {
              params: {
                season: "SEASON2015",
                api_key: token
              }
            })
            .success(function(response, error) {
              
              response.playerStatSummaries.forEach(function(entry) {
                  if(entry.playerStatSummaryType=="Unranked"){

                    data.norank5x5=entry;
                  }
                  if(entry.playerStatSummaryType=="CAP5x5"){
                    data.team5x5=entry;
                  }
                  if(entry.playerStatSummaryType=="Unranked3x3"){
                    data.unrank3x3=entry;
                  }
                  if(entry.playerStatSummaryType=="RankedTeam3x3"){
                    data.rank3x3=entry;
                  }
                  if(entry.playerStatSummaryType=="RankedTeam5x5"){
                    data.rank5x5=entry;
                  }

                  
              });

            });

        });

        return date;
        }
        
    };
});

When using this factory in the controller and clicking, an issue of getting "undefined" arises, so how can the object be retrieved?

.controller('MainCtrl', function($scope,$rootScope,$ionicLoading,API) {

  $scope.showmenu = function(){
        console.log(API.Getalldata("fenix"));
    }

});

Answer №1

To retrieve the $http within the function, proceed by executing the following in the $scope method:

API.Getalldata("something").then(function(response) { console.log(response) });

I must mention that I have not personally tested this approach, but it is expected to be effective in resolving your issue.

On a side note: attempting to return the date/data is futile since $http functions as a promise and the value will not be resolved at the intended time of retrieval.

Answer №2

It appears that the issue lies in your code where you are returning "date" instead of "data".

angular.module('starter.services', [])

.factory('API',function($http){
var data={};
var token = "****";
return{
    Getalldata : function(name){

     [..edited..]

    });

    return data; // THIS IS LIKELY WHERE THE ERROR OCCURS
    }
    /*getRankData : function(name,sezin){

        mydata = "kola";
        return mydata;

    }*/
};});

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

Error: Next.js is throwing a SyntaxError due to encountering an unexpected token 'export'

I encountered an issue when trying to render the following code: SyntaxError: Unexpected token 'export' (project path)/node_modules/react-syntax-highlighter/dist/esm/styles/prism/index.js Everything seems to work as expected initially, but then ...

Unable to update innerHTML of asp.net literal tag using JavaScript

Here is a snippet of my JavaScript code: <script type="text/javascript">function CountCharacters(idTxtBox, idCharCount) { var maxLimit = 500; var remainingChars = maxLimit - document.getElementById(idTxtBox).value.length; do ...

I was disappointed by the lackluster performance of the DataTable in CodeIgniter; it did not

I recently started using CodeIgniter and I'm having trouble getting the dataTable to work. Here's a snippet of my page: <table class="table table-striped table-bordered table-hover dataTables_default" id="dataTables-example"> ...

The image fails to load smoothly in the midst of an ajax operation

Here is my code snippet... div used for displaying content along with a loading image: <div id="adS" style="float: left; width: 70%"> <div id="loading-image" style="background-image: url('images/processing.gif'); display: none;"> ...

Expanding on the nested document in mongoose

I have been working on setting up a nested mongoose document configuration in the following manner: models/data.js var mongoose = require('mongoose'); var addresses = new mongoose.Schema({ "street": String, "city": String, "state": Stri ...

Trouble accessing $rootScope in Angular's config phase?

I am currently working on: myApp.config([ '$httpProvider', '$rootScope', function($httpProvider, $rootScope) { $httpProvider.interceptors.push(function($q) { return { responseError: function(rejection) { ...

Combining the powers of Rails API with AngularJS and the Websocket-Rails gem

Currently, my server is utilizing the websocket-rails gem for managing websockets. I am encountering challenges integrating websocket-rails with a phonegap project that incorporates angular. This is because I require the ability to initialize the websocke ...

Setting ng-model object with expression in AngularJs can be accomplished by using the Update/Assign

Currently, I am utilizing the MEAN stack in my application with AngularJS as the frontend. I have a question regarding how to use ng-bind to display the total sum of a value in another input in AngularJS. In my scenario, I have a table where I'm using ...

Tips for effectively implementing React.usecallback

Looking for a way to rewrite the handleClick method using React.useCallback in a function called Parent, which is triggered by a button click event in React and TypeScript. function Parent () { const [isOpen, setIsOpen] = React.useState(false); ...

Arrays containing references to Javascript objects

Recently, I've observed some odd behavior with one of my arrays. It seems that the issue lies in how Javascript stores object references within arrays. To illustrate this problem, I'll share a code snippet that I previously posted as an answer on ...

MEAN Project - Organizational Endeavors

Can anyone share their recommended practices for developing a Single Web Page app project using the MEAN stack (MongoDB, Express, Angular and Node.js)? Our current setup involves: One repository for the Angular client-side code Another repository for th ...

Why does the Google Places API consistently provide latitude and longitude values under varying variables each time?

I am completely baffled by this situation. Initially, the API was returning the Latitude and Longitude like this: (I believe it was in this format): place.geometry.location.y as Latitude place.geometry.location.z as Longitude Then it suddenly change ...

There was an issue encountered when attempting to access the stackoverflow api

I am currently attempting to retrieve all questions tagged with ipv4 from stackoverflow using the stackoverflow API. However, I encountered the following error message: No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

Concealing a section of a table with JavaScript while preserving the original table structure

I made some adjustments to the script tag: $(document).ready(function) { Now, the evenTd's are hidden correctly. Here is the table with the code provided: <table> <tr> <td>itemOne</td> <td class="even ...

Sending a response with Express before an asynchronous function has completed

app.get('/test',(req,res)=>{ doSomething().then(res.sendFile(path,(err)=>{ if (err) { console.log('err') } else { console.log('Sent:', fileName) } })) asyn ...

Converting a string into a regular expression using JavaScript

I am attempting to change the color of a text element when specific variations of the word "hello" are entered into an input field. While this works with a regular string comparison, it fails when using a regular expression. <input id="input" type="inp ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...

When the URL contains a "#" symbol, the $http.post request is being cut off

I have a Rest API endpoint: /myApp/fetchData/User-Name/Password. The User-Name and Password values are variable depending on the request. When making a call to this API like this: /myApp/fetchData/srikanth/Abcdef#g123 the actual request is sent as follo ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

What is the best way to trigger a 'Save As' dialog box on a browser when a button is activated within an Angular application, guaranteeing cross-browser compatibility?

The solution needs to be compatible with both Windows and Mac operating systems. Additionally, we should be able to specify a default file name and type. ...