Mixing resource and non-resource techniques in Angular factory

Feeling a bit confused by what should be a simple task. I am currently working on enhancing an Angular service by adding some new methods. Initially, the service was only making a single $resource call to my API. The additional methods I am incorporating are basic functions that save and retrieve a local object:

'use strict';

angular.module('gameApp')
  .factory('searchService', ['$resource',
    function($resource) {
      var base = '/api/search?query=:query';
      var latestResults = {};

      return $resource(base, {}, {
        getResults: {method: 'GET', url: base}
      }),
      saveLatest: function(results) {
        latestResults = results;
      },
      getLatest: function() {
        return latestResults;
      }
    }]);

It appears that the structure above is incorrect, particularly in relation to the saveLatest and getLatest functions.

Answer №1

The current setup you have will return multiple values separated by commas simultaneously, which is not feasible (assuming this is not ES6). You should either return an array or object containing the three return values:

return [
  $resource(base, {}, {
    getResults: {method: 'GET', url: base}
  }),
  function(results) {
    latestResults = results;
  },
  function() {
    return latestResults;
  }]

or

return {
    resource: $resource(base, {}, {
        getResults: {method: 'GET', url: base}
    }),
    saveLatest: function(results) {
        latestResults = results;
      },
    getLatest: function() {
        return latestResults;
    }
}

Moreover, exposing the entire $resource object is typically unnecessary, so it might be more appropriate to just return the getResults method of it.

Answer №2

Your return object should be structured like this:

return {
   method1: function(){...},
   method2: function(){...},
   method3: function(){...},
};

However, your current structure is different:

return method1(),
       method2: function(){...},
       method3: function(){...}

It's important to pay attention to these differences.

Based on the documentation, your code should follow a pattern similar to this:

return {
    getResults: $resource(base,{method: 'GET', url: base}),
    saveLatest: function(results) {
        latestResults = results;
    },
    getLatest: function() {
        return latestResults;
    }
}

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

explore the route with the help of jquery scrolling feature

Is there a way to implement scrolling functionality for tab headers similar to this demo? I have a list of elements within a div that I need to scroll like the tabs in the demo. I attempted to achieve this by setting the position of the inner elements to ...

Debug mode in React Native using hooks may encounter discrepancies in data stored in AsyncStorage

I am working on a project where I have two separate screens connected with a simple react native stack router. The second screen contains choice blocks that set state using useState and AsyncStorage. Every time the screen is entered, it reads the state of ...

Consistent surface appearance across combined mesh

Is there a way to texture a merged mesh from geometry as one solid piece rather than separately on each individual shape? In the provided code snippet, the textures are applied to separate geometries (refer to image points 1 and 2) - two Cubes and one Cyli ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Navigating within an ionic framework

I am facing an issue with a simple form in my application. When I try to enter user details, the Android keyboard hides the email field and mobile number field, making it impossible for me to scroll the page upwards. Can anyone suggest a solution? <i ...

Wait until the npm.load callback is returned before returning module.exports

I am currently facing a situation similar to the one depicted in this simplified example. main.js var settings = require('../settings.js'); console.log(settings.globalData); //undefined The settings.js file relies on an external module (npm) t ...

Identifying clicks on various indices within a common class or element

My website has a navigation menu with unordered list items in it. <nav> <ul> <li id="zero"></li> <li id="one"></li> <li id="two"></li> </ul> </nav> I am working on implementing J ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...

JavaScript Global Variables Keep Getting Reset

Here's the concept behind my project: I've created a simple game that utilizes a do/while function and a switch statement to determine the player's current room. When the player is in room 1, the switch selects room1 and executes the room1() ...

When dealing with errors in fetching JSON data, consider implementing a robust error handling strategy and

Is there a way to provide a fallback JSON string in case the fetch URL fails to connect? const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`) ...

Ways to determine if the navigation bar is in a collapsed state or not

I am working with a navbar: <nav id="navbar" class="navbar fixed-top navbar-expand-md navbar-light bg-light"> <a class="navbar-brand" href="#"></a> <button id="toggle" class="n ...

Hovering over the child element, instead of the parent

I'm working on implementing a highlight feature for my website. The structure of the HTML looks something like this: <div> <!-- this is the main container --> <div> content ... </div><!-- a child element --> < ...

What steps can I take to display a "Sign in with Paypal" button on a React App?

Disclaimer: I am relatively new to React and have only been dabbling with it for a day. I came across this tutorial source code that is designed for logging in with Google. https://github.com/The-Tech-Tutor/spring-react-login My goal is to integrate a "L ...

Using JavaScript to show content in a textarea field

In my index.jsp file, I have implemented the following code to populate two textareas, INPUT_TEXT and INPUT_TEXT2, with processed data. This involves passing the text through a servlet, a Java class, and finally displaying the preprocessed results in the s ...

I'm having some trouble with my jQuery.get() function in the javascript Saturday(), can anyone help me figure out what I'm doing wrong?

Can anyone help me troubleshoot my jQuery.get() method in the saturday() JavaScript function? Here is the code snippet I have been working on. This is what I have in my index.html file: <html> <head> <title>jVectorMap demo</title> ...

Issue encountered when importing async function: Invalid hook call. Hooks are designed to be called only within the body of a function component

All I desire is the ability to access logic from my geolocationApi file in my react-native components without using a hook. Instead, I prefer normal asynchronous functions. The geolocationApi file employs a custom hook for handling mobx state updates, whic ...

SyncHistory middleware for Isomorphic React-Router-Redux

The usage of syncHistory from react-router-redux involves passing the argument browserHistory from react-router. However, when attempting to call syncHistory(browserHistory) on the server, it does not function as expected. The objective is to establish a s ...

Uncovering the secrets: accessing hidden folder files in react-native-fs

I am encountering a problem when trying to access files from a hidden folder /WhatsApp/Media/.Statuses in react-native-fs. Despite granting the READ_EXTERNAL_STORAGE permission on Android, I only receive an empty array when attempting to access it using th ...

Exploring the World of Html

I'm struggling with an HTML problem related to a web programming class I'm taking. The assignment involves creating a video game using HTML and JavaScript, where an image moves randomly on the screen and the player must click on it as many times ...

Comparing a number to the sum of numbers in JavaScript using VUE

Newbie in the world of JavaScript and VUE. In my data, I have a variable called numberOfItems with a value of 10. I am trying to check if this value is equal to the total sum of 5 different variables. var numberOfItems = 10 var destinations = (this.campa ...