What is the process of invoking a service from a controller?

In my MovieSearchCtrl controller class, I have a method called returnMovies(query) that looks like this:

returnMovies(query): any {
    return MovieSeat.MovieSearchService.getMovies(query);
}

Within the MovieSearchService service class, there is a function named getMovies(query) defined as:

getMovies(query) {
    let baseURL = "http://api.themoviedb.org/3/";
    return this.$resource(baseURL + "search/movie?api_key=a8f7039633f2065942cd8a28d7cadad4&query=" + query + "&callback=angular.callbacks._0");
}

In order to utilize the data returned by the getMovies() function within the MovieSearchCtrl constructor, I want to assign it to this.results. How can I achieve this?

Answer №1

To easily access movie search functionality within MovieSearchCtrl, simply inject MovieSearchService and proceed to invoke the getMovies() method as shown below:

.controller('MovieSearchCtrl ',function(MovieSearchService, $scope){
      $scope.movies =[];
      $scope.search={}; //ng-model for your input

      MovieSearchService.getMovies($scope.search.query).then(function(res){
      $scope.movies = res.data;
    });
  });

Answer №2

.factory('MoviesAPI', function($resource, apiHost) {
  return $resource(apiHost + '/movies/:Id'); 
});

In order to utilize the service within the controller, you must inject it.

.controller('filmController', function($routeParams, MoviesAPI) {
        var vm = this;

        vm.moviesList = [];
        var movieResource = MoviesAPI.query();

        vm.getMoviesList = function (){
              movieResource.$promise
                .then(function(response) {
                 vm.moviesList = response;
                }, function(error) {
                    // Handle errors here
                });
              };
        };

    });    

Hopefully this information proves useful.

Answer №3

Just a couple of simple steps to follow.

  1. If the code is located in a different module, ensure it is listed as a dependency in your module definition

    angular.module('MovieSearchCtrl', ['MovieSearchService']);
    
  2. Next, remember to inject it into your controller definition

    MovieSearchCtrl(MovieSearchService){
       this.movies = MovieSearchService.getMovies():
    }
    angular.controller('MovieSearchCtrl', MovieSearchCtrl);
    

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

Utilizing TypeScript for various return types with the same parameters

Exploring TypeScript Signatures In an effort to embrace TypeScript fully, I am implementing strongly typed signatures in my Components and Services, including custom validation functions for angular2 forms. I have discovered that while function overloadi ...

Generating a registration key for a Laravel application using a distinct frontend application

I am in the process of developing an Angular application that will be connected to a separate Laravel backend. My focus at the moment is on user authentication, specifically user registration. However, I have encountered some errors along the way: Error ...

Schema Connections in Kendo Diagram

I am currently experimenting with the Telerik Kendo diagram in an attempt to create a visual representation. Due to the fact that I am retrieving all shapes and their connections from my database, I encountered an issue where the attributes of my data sour ...

AngularJS modal popup with a selectable table

Is there a way to open a modal popup containing a table in my application? I'm trying to achieve this by setting up an event in my app.js that triggers the modal when a row is clicked. Additionally, I need to update a field with the selected item&apos ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

I'm looking for a way to create a Redux thunk action creator that will return a promise. How

In my code, I have a primary thunk that is triggered by a button click. Within this thunk, I need to invoke another thunk and ensure it completes before proceeding. The second thunk returns a promise. Below is an excerpt of the code in question: export f ...

Collapse the accordion when the search query is less than or equal to 0

I'm having trouble making the accordion open both when the user has typed something into the search bar and when someone clicks to open it. I can get them to work individually, but not together. If I use this code: <accordion-group is-open="statu ...

JavaScript Email Validation

Check out my JavaScript code below: $scope.isValidEmailAddress = function(emailAddress) { // var pattern = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/); var pattern = new RegE ...

The response code in the API remains 200 despite setting the status code to 204 in NestJS

I have developed an API that needs to return a 204 - No Content Response import { Controller, Get, Header, HttpStatus, Req, Res } from '@nestjs/common'; import { Response } from 'express'; @Get("mediation-get-api") @Head ...

Steps for converting an Array of tuples into a Union of Tuples

I am attempting to develop a custom type that, when given an array of tuples as input, will generate the union of each index within the tuple. This may not be the most accurate terminology, but I hope you understand what I mean. const entries = [["name", ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

Simple method for securing and unsecuring uploaded files in a directory with the use of AngularJS and a PHP framework

I've been exploring options for encrypting and decrypting files, specifically .pdf files. After researching and experimenting with codes like crypto.js, I'm still struggling to grasp the process. Can someone provide guidance on how to achieve thi ...

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...

VSCode's Formatting Feature Adds Spaces and Line Breaks to Angular HTML in Certain Files

When I try to use the Auto Formatter on certain HTML files in my Angular/MEAN Stack app, it causes some strange issues with the angular code. The main problems are as follows: Extra spaces added at the end of quoted attributes <div class="hello"> ...

Troubleshooting: Ngx-Echarts Animation Issue at Startup

I've been working on integrating ngx echarts into my Angular app, but I'm facing an issue with the animation during the initial load of the chart. Take a look at this Stackblitz example where you can see that the bars render quickly on initial lo ...

I am having trouble with getting the templateUrl to function properly

Recently diving into Angular, I am currently working with Angular-UI-Router in combination with ASP.NET MVC 4. app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.other ...

Tips for customizing the appearance of Ionic's navigation bar

I attempted to customize the background-color of an ion-nav-bar by using the following code: <ion-nav-bar class="backarrow-bar" ng-style="{'background-color': rgba(255, 0, 0, 0.5)}" style="background-color:rgba(255, 0, 0, 0.5)"> <io ...

Angular seems to be experiencing issues with maintaining context when executing a function reference for a base class method

Imagine we have CtrlOne that extends CtrlTwo, with a componentOne instantiated in the template of CtrlOne. Here is some code to illustrate the issue: class CtrlOne extends CtrlTwo { constructor() { super(); } } class CtrlTwo { sayMyName(name: st ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Various types of controllers in Angular depending on user authentication

Currently, I am working on an app that utilizes JWT authentication. In order to navigate within the app, I am using $stateProvider. The server sends a token along with a boolean parameter (isAdmin) in JSON format. My question is, is it possible to load a ...