The API call within the app's service.js is not communicating with the page's controller

When my app accesses an API, it retrieves an array of 'card' objects and showcases each one on the user interface.

The HTML file for card search is: card-search.html

<div class="main-view container">
    <h1>Card Search</h1>

    <div id="card-search" ng-controller="cardSearchController">

            <form class="search-form">
               <p>Retrieve card information via name or multiverse ID</p>
                <input ng-model="cardInput" type="text" name="" value="">       
                <select ng-model="selectedItem" ng-options="item as item.label for item in items"></select>
                <button ng-click="getCard(cardInput)" type="button" name="button">Search</button>
            </form>

            <div class="container result-container">

                        <div ng-repeat="card in displayedCards" class="row display-row">
                            <div class="col-sm-6 card-display">
                                <img src={{card.imageUrl}} alt="">
                            </div>
                            <div class="col-sm-6 card-stat-display">
                                <p><strong>Name:</strong> {{card.name}}</p> 
                                <p><strong>Mana Cost:</strong> {{card.manaCost}}</p>
                                <p><strong>Converted Mana Cost:</strong> {{card.cmc}}</p>
                                <p><strong>Colors:</strong> {{card.colors}}</p>
                                <p><strong>Type:</strong> {{card.type}}</p>
                                <p><strong>Text:</strong> {{card.text}}</p>
                                <p><strong>Flavor Text:</strong> <i> {{card.flavor}}</i></p>
                                <p><strong>power:</strong> {{card.power}}</p>
                                <p><strong>Toughness:</strong> {{card.toughness}}</p>
                            </div>   

                        </div>
            </div>            
    </div>

The intention here is to showcase every card in cardDisplay, which is a collection of objects.

The controller responsible for this functionality is located at cardSearchController.js

angular.module('mainApp').controller('cardSearchController', function($scope, mainService) {

$scope.getCard = function(searchInput) {

    console.log('$scope.selectedItem.label', $scope.selectedItem.label)
    if ($scope.selectedItem.label === 'Search By Multiverse ID') {
        mainService.getCardById(searchInput).then(function(card){
            $scope.displayedCard = card;
        })
    }

    if ($scope.selectedItem.label === 'Search By Name') {
        var searchInput = searchInput.split(' ').join('+')
        mainService.getCardByName(searchInput).then(function(uniqueCards){
            console.log('unique cards in controller', uniqueCards);
            $scope.displayedCards = uniqueCards;
        })
    }

};

$scope.items = [
    {
        label: 'Search By Name'
    },
    {
        label: 'Search By Multiverse ID'
    }
]

});

This script defines the logic that should pass back uniqueCards.

The service related to this operation can be found in service.js:

angular.module('mainApp').service('mainService', function($http, 
$state) {


this.getCardByName = function(name) {
    console.log(11111, 'I am here');
    return $http({
        method: 'GET',
        url: 'https://api.magicthegathering.io/v1/cards?name=' + name + '&contains=imageUrl'
        }).then(function(response) {

            console.log(response.data);
            var returnedCards = response.data.cards;
            var uniqueCards = [];
            console.log('the contents of returned cards: ', returnedCards);

            for (var card of returnedCards) {
                var testedCard = card;
                var uniqueName = true;

                for (var uniqueCard of uniqueCards) {

                    if (testedCard.name === uniqueCard.name) {                            
                        uniqueName = false; 
                        break;
                    }
                }
                if (uniqueName) {
                    uniqueCards.push(testedCard);
                }
            }

            console.log('here are the unique cards: ', uniqueCards);
            return uniqueCards;

            }), 
            function (cards) {
                alert('An Error', cards);
            };
}

This service sets up the retrieval process where this.getCardByName aims to provide uniqueCards back to the controller.

Despite successful creation of uniqueCards according to our logs, the controller doesn't seem to be receiving it. Moreover, the development console indicates an issue with invoking mainService.getCardByName:

angular.js:14642 TypeError: mainService.getCardByName(...).then is not a function
at ChildScope.$scope.getCard (cardSearchController.js:14)
at fn (eval at compile (angular.js:15500), <anonymous>:4:223)
at callback (angular.js:27285)
at ChildScope.$eval (angular.js:18372)
at ChildScope.$apply (angular.js:18472)
at HTMLButtonElement.<anonymous> (angular.js:27290)
at HTMLButtonElement.dispatch (jquery-3.2.1.min.js:3)
at HTMLButtonElement.q.handle (jquery-3.2.1.min.js:3)

It seems that calling getCardByName suggests it's undefined, even when the corresponding script tag exists within index.html.

Answer №1

The error message is not indicating that getCardByName is not a function, but rather that getCardByName.then() is not a function. This suggests that you have already called the .then() method in your mainService.

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

Troubleshooting a config file problem related to prefixes

While exploring discord.js at , I encountered a problem that has me stuck. Index.js const Discord = require('discord.js'); const { prefix, token } = require('./config.json'); const client = new Discord.Client(); client.on('ready& ...

What happens when tabs are dynamically added on keypress?

I am encountering issues with this code snippet. $('body').on("keypress", ".message", function(e) { if ( e.keyCode == 13 && $(".message").val().length > 0 ) { input = $(".message"); // Check for join com ...

activate the bootstrap popover by double-clicking instead of a single click

Clicking on a certain div triggers a popover to display another div, which works initially. However, once the popover is removed by clicking outside the div, it requires two clicks to trigger the popover again. How can this be fixed so that it always works ...

What methods are available to incorporate arithmetic when defining a style attribute?

Is there a way to achieve arithmetic operations in CSS, like calculating margin-left: -60px + 50% of the width of the parent div? I'm eager to find a solution, whether it involves JavaScript or any other method. Any help would be greatly appreciated. ...

Refresh database post drag and drop operation

I am seeking a way to update a "state" SQL row after dragging an element between the "DZ", "WT", and "ZK" divs. Below is a snippet of my code: SQL queries: $sql = "select * from tasks where login = '$user_check' AND state = 1"; $sqlDodane = mys ...

Charting multiple datasets in a line graph based on provided tabular

I am currently working on generating a multi-set line graph using Chart.js and Angular. With the help of map function, I have been able to transform the JSON data into a single-dimensional array. However, my challenge lies in converting one of the columns ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Transforming Google Maps from using jQuery to AngularJS

If I have a Jquery google map with find address and routing system, my goal is to convert it to an angular google map with more options. The current Jquery google map code looks like this: var directionsDisplay = new google.maps.DirectionsRenderer({ d ...

Order a nested array according to the inner value, using a different array as a reference

Having two arrays at hand, array1 requires sorting based on its inner key, role, as per array2. Despite attempting various solutions, I have hit a roadblock due to my lack of understanding on the necessary steps to proceed. The current output for Array1 i ...

What is the most efficient method for toggling a button's id between two different states in JavaScript

Looking for some help with a button situation... <a id="fullcollapse" class="btn btn-lg btn-primary" href="#" role="button">Collapse menu &laquo;</a> I want to dynamically change the ID of this button onclick to "baseexpand", and then re ...

Ways to conceal images until AFTER the completion of the jquery flexslider loading process

After trying to integrate wootheme's Flexslider on my website, I encountered a small issue with its loading process. Whenever the page is refreshed with the slider, there is a brief moment (approximately 1 second) where the first slide appears overly ...

Migration from Rails to Angular - Dynamically load tab content

Deciding whether to migrate all of my frontend to Angular, I am working on converting one of my RoR web pages. The issue I am facing is with routing - the routes configured by rails seem to take over the request, causing the entire layout to reload instead ...

What could be causing the misalignment of my request and response messages?

Currently, I am going through a Node.JS basics book and have successfully created two programs - one responder and one requester. The responder: "use strict"; const fs = require("fs"); const zmq = require("zmq"); const responder = zmq.socket("rep"); // ...

The .map function doesn't seem to be functioning properly in the React application

I am facing an issue with the .map method of the object from the API I imported. Despite being able to see the object in the browser console, I cannot interact with it. This component is called "races" const BASE_URL = "https://www.dnd5eapi.co/api/races"; ...

AngularJS allows you to toggle the visibility of a div at set intervals, creating

I am struggling with the task of showing and hiding a div that serves as an alert for my application. Currently, I am using $interval to create a continuous show and hide action on the div. However, what I aim for is to have the DIV visible for X amount o ...

Create sleek and custom forms with AngularJS and JQuery

As a core C++ developer, I have recently expanded my skills to include Scala, Lift, and AngularJS. My latest project involves developing an application similar to . There is a high possibility of needing to modify existing features or introduce new ones t ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...

Guide to handling HTTP request parsing in Express/NodeJs when the content type is missing, by setting a default content type

Is it possible to retrieve POST data in an express request when the bodyParser does not work? var server = express(); server.use(express.bodyParser()); server.post('/api/v1', function(req, resp) { var body = req.body; //if request header doe ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...