Can someone guide me on passing functions from a service to the controller and invoking them using AngularJS ES6 syntax?

Whenever I attempt to invoke the getTodos function in the controller, it seems to be returning no value. I am trying to store the value returned by the getTodos() function into this.todos. However, this.todos keeps returning null.

/* ----- todo/todo.service.js ----- */
   class TodosController {
   constructor(TodoService) {
    'ngInject'
    this.ArtistsListService = ArtistsListService;
   }

    $onInit() {
      this.todos = null;
      this.TodoServiceService.getTodos().then(response => 
 this.todos = response);
      console.log(this.todos);
    }
}

export default TodosController;`

/* ----- todo/todo.service.js ----- */
   export class TodoService {
  constructor($http) {
    'ngInject';
    this.$http = $http;
  }
  getTodos() {
    return this.$http.get('/api/todos').then(response => 
 response.data);
  }
}

/* ----- todo/todo.module.js ----- */
 import angular from 'angular';
 import { TodoComponent } from './todo.component';
  import { TodoService } from './todo.service';
 import './todo.scss';

 export const TodoModule = angular
  .module('todo', [])
  .component('todo', TodoComponent)
  .service('TodoService', TodoService)
  .name;

Answer №1

Consider using the following code snippet for your TodoService:

export class TodoService {
  constructor($http) {
    'ngInject';
    this.$http = $http;
  }
  getTodos() {
    return this.$http.get('/api/todos');
  }
}

Then, in your controller, you can utilize the following:

   class TodosController {
   constructor(TodoService) {
    'ngInject'
    this.ArtistsListService = ArtistsListService;
   }

    $onInit() {
      this.todos = null;
      this.TodoServiceService.getTodos().then(response => 
        {
           this.todos = response.data;
           console.log(this.todos);
        },
        (error) => { console.error(error) }
       );

    }
}

export default TodosController;

Ensure that you are returning the $http promise like this:

return this.$http.get('/api/todos')

This will allow you to work with promises in your service file effectively.

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

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...

What does React default to for the implementation of the ``shouldComponentUpdate`` lifecycle method in its components?

Having a personalized approach to the shouldComponentUpdate() method as part of the React component lifecycle is not obligatory. I am aware that it serves as a boolean function determining whether the render() function will be triggered by changes in comp ...

Verify if the value in a textbox exceeds the number entered in an array of textboxes

My goal is to compare the value of a single text box, labeled as "totalmarkstoall", with multiple arrays of text boxes labeled as "marksscored". The JavaScript code below is set up to compare these values using a key up function. The issue I am facing is ...

What could be causing the entire app to malfunction when the Redux Provider tag is used

I am facing an issue while trying to integrate a React Toolkit app into my project. The error message I encountered is as follows: Error: Invalid hook call. Hooks can only be called inside the body of a function component. This error may occur due to one ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

AngularJS withCredentials Issue causing data not to be transmitted

When using AngularJS, I encountered an issue where the cookie/session was not being shared across domains for my Restful API in a subdomain. To address this problem in Angular, I added the following configuration: app.config(['$httpProvider', fu ...

Guide on accessing the final value of a text file using JavaScript

My server side script outputs results in a txt file, where the values stored look like this: 1 2 5 7 10 In order to create a real-time progress bar, I need to fetch the last value from the file using an ajax request while updating the txt file with the l ...

Received an unexpected character '?' in NextJS

After setting up a fresh installation of Ubuntu 22.04.1 LTS and installing npm and docker, I encountered an issue while trying to start my NextJS web server with the command npm run dev. An error message appeared as follows: niklas@srv-code01:~/Desktop/Co ...

Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs. I'm currently working on creating a new user document ...

Create a duplicate of a div using JavaScript and modify the IDs of the inner elements within

I have two static div tags with a select tag and a text box inside, each with different IDs. When I clone the tag, it duplicates the same div tag in the DOM. How can I change the inner elements' tags? Below is the code snippet: <div id="m ...

Include a suffix after the user's input in a Material UI TextField

I need to implement a TextField element that displays the entered value followed by an Input Adornment. Can I have the percentage sign (%) appear after the entered value instead of at the end of the input? Currently, the percentage sign (%) appears at the ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

Removing a cookie in Javascript - step by step guide

Cookie Conundrum: I've encountered a curious scenario involving browser cookies. After entering an invalid login ID, an unauthorized cookie appears on my HTML page. Despite my attempts to display and expire the cookie, it stubbornly remains persistent ...

HTML5 Slideshow with Smooth Image Transitions

So, I have created an HTML5 image slideshow and it's working perfectly on my localhost. However, I am puzzled as to why there is no transition effect within the slideshow. I was expecting something like fading out the first picture and then having the ...

Using Angular JS: Implementing ng-repeat with a personalized directive and a fluid model

I have a template structured like this: <div class="row search-panel"> <div ng-show="loadingAirports"> <i class="glyphicon glyphicon-refresh"></i> Searching... </div> <div ng-show="noResults"> ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

Is it safe to securely store connection credentials in javascript?

I am currently working on developing a web chat app for a Minecraft server using this API. However, the demo script I am referring to displays connection information in plain text, making it easily visible to any client's computer. Is there a way to s ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...