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

The AngularJS OpenLayers directive encounters issues when used inside an Angular-UI dialog component

I am interested in integrating the AngularJS OpenLayers directive into my webpage. It seems to work fine on its own, but when I try to use it within angular-ui-dialog, it does not function. Despite checking the console for errors, I am unable to determine ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

Mapping a Tuple to a different Tuple type in Typescript 3.0: Step-by-step guide

I am working with a tuple of Maybe types: class Maybe<T>{ } type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>]; and my goal is to convert this into a tuple of actual types: type TupleIWant = [string, number, boolea ...

Using TypeScript TSX with type parameters

Is it possible to define type parameters in TypeScript TSX syntax? For instance, if I have a class Table<T>, can I use something like <Table<Person> data={...} /> ...

Incorrect ng-pattern does not enable the tooltip to be activated

I have implemented the ng-pattern="/^[0-9]{9}$/" in an input field that appears as follows: <input type="text" id="company_taxId" ng-model="company.taxId" required="required" class="input ng-scope ng-valid-maxlength ng-valid-mi ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...

What is the rationale behind not passing $scope to a service in AngularJS, and is it considered bad practice?

Is it advisable not to pass $scope to a service for certain reasons? I understand that services are intended to be reusable singletons, and passing a (potentially) large object to the service could lead to maintenance issues. However, assuming there is so ...

Is there a way in AngularJS to iterate through the properties of one object and assign them to the corresponding properties of another object?

I think I might need to work with strings and a forEach statement for this. I'm relatively new to Angular, but basically what I want to achieve is: I have two objects - object 1 and object 2. Object 1 contains all the variables that are also present ...

Having trouble dispatching a TypeScript action in a class-based component

I recently switched to using this boilerplate for my react project with TypeScript. I'm facing difficulty in configuring the correct type of actions as it was easier when I was working with JavaScript. Now, being new to TypeScript, I am struggling to ...

Linking Redux to the highest level of my application is not functioning as expected

I have been attempting to troubleshoot this code for quite some time now, but I am struggling to identify the issue at hand. My main goal is to establish a connection between my top-level application and the redux store. However, every time I try, the stor ...

The autofocus feature on the textarea in Angular Material Dialog seems to be malfunctioning

Within a web app, I am utilizing the Dialog component from Angular Material. The Dialog consists of only a textarea that is initially empty. I aim to automatically focus on the textarea when the user opens the modal dialog. How can I achieve this? Despite ...

Troubleshooting: Unable to Open Page with Google Material Button in Angular 5

Currently, I'm facing an issue with a button that is not opening to a new site despite following what seems like simple steps. <button mat-raised-button href="https://www.google.com/" color="primary">Connect with Stripe</button> I even a ...

AngularJS Apply Class to list items that do not match

I have successfully implemented a Filter with a Select-Field in my list. <div ng-controller="streamsController" class="stream-list-wrap"> <div class="form-field"> <select id="selectedGenre" ng-model="selectedGenre" ng-o ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Refining types in a series of statements

I'm attempting to merge a series of assertions in a safe manner without the need to individually call each one. For instance, consider the following code: type Base = { id: string, name?: string, age?: number }; type WithName = { name: string }; type ...

Navigating with AngularJS in an ExpressJS Server

I currently have a setup consisting of an AngularJS app running on a NodeJS server with ExpressJS. I am serving the Angular app as static files using the following code: app.use(express.static(__dirname + '/app')); One issue I encountered is th ...

I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images. If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select. This ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs) PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED Failed: Uncaught (in promise): Error: Templ ...