Invoke a fresh constructor within a $get method in Angular's provider

I'm encountering an issue where I am attempting to utilize a function as a constructor inside the `.provider`, but I'm unable to instantiate a new constructor when it's within the `$get`.

Here is my provider setup -

 this.$get = $get;
    $get.$inject = ['checkUrl', '$log', '$location'];

    function $get(checkUrl, $log, $location) {
        return {

            moduleCon: function(name, cb) {
                    //my constructor function
                }

            }

When I try to inject and call it like this

   new  myProvider.$get().moduleCon("name", "cb");

I encounter an injector error.

However, if I move it outside of the $get, it works as follows:

   (inside the provider above the $get)
    this.moduleCon = function(name, cb) {
                    //my constructor function
                }

I need to use `this.`, but then I can successfully call

   new myProvider.moduleCon("name","cb");

And it works correctly. Is there any way to expose it in the $get as a constructor as I am doing here? Thank you!

Answer №1

The code you currently have is being interpreted as:

(new myProvider.$get()).moduleCon("name", "cb");

This isn't achieving the desired result. To achieve what you want, you need to write it like this:

new (myProvider.$get().moduleCon)("name", "cb"); // or
new (myProvider.$get()).moduleCon("name", "cb");

It's recommended to avoid creating constructor functions dynamically.

Answer №2

When you invoke myProvider, what you are really invoking is the $get function associated with it. In essence, there is a line of code that triggers the injector's invoke method:

instanceInjector.invoke(provider.$get, provider, undefined, serviceName);

While there are many intricate details at play, the crux of the matter is that the value returned from the $get function is essentially what myProvider represents. If you were attempting something specific, it would be realized by structuring it in this manner:

app.controller('MainCtrl', function($scope, myProvider) {
  myProvider.$get();
});

app.provider('myProvider', function() {
  this.$get = function(){
    return {
      $get: function(){console.log('something isn\'t right here...')}
    }
  };
});

Though this example may seem nonsensical, it serves as a learning experience to grasp the inner workings of this concept better. Remember, the $get function plays a crucial role in retrieving whatever the provider offers. Essentially, a factory mirrors a provider, but with its $get method being the function passed to the app.factory method:

function factory(name, factoryFn) {
    return provider(name, { $get: factoryFn });
}

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

Can you explain the meaning of the symbol '&$checked'?

import React from 'react'; import Checkbox from '@material-ui/core/Checkbox'; import { createMuiTheme, makeStyles, ThemeProvider } from '@material-ui/core/styles'; import { orange } from '@material-ui/core/colors'; ...

What steps should be taken to ensure that the onmouseover and onmouseout settings function correctly?

The Problem Currently, I have a setup for an online store where the shopping cart can be viewed by hovering over a div in the navigation menu. In my previous prototype, the relationship between the shoppingTab div and the trolley div allowed the shopping ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Transitioning from using $http to Restangular has caused issues with our tests now not passing

I am currently working with the following controller: 'use strict'; angular.module('App') .controller('LoginCtrl', function ($scope, $state, Login, localStorageService, Message, authService) { $scope.submit = function ...

Encountered an EACCESS error while attempting to generate package.json in Angular

Upon completing the command line "yo angular" and following all the necessary steps, I encountered this error : Screenshot of the error I attempted to run it using "sudo yo angular" but unfortunately, it did not resolve the problem. Does anyone have any ...

How can we incorporate a Material-UI skeleton to display API response data effectively?

I have incorporated the material-ui skeleton (Shimmer effect) to display data fetched from an API. { accountData.usersAccountData.map((userData, index) => ( // ...UI code ) ) } The output is shown below : https://i.sstatic.net/MEVhA.png It can be o ...

Finding your site's First Contentful Paint (FCP) can be done by analyzing the

After doing some research on Google insights, I came across information about FCP. However, I'm still unsure about how to determine my site's FCP and other relevant metrics. If anyone could provide me with more information or share detailed link ...

Leveraging the power of JavaScript to retrieve data from PHP/MySQL

Considering creating an Android app using Appcelerators Titanium application and have a question. The website for the app is built with PHP/MySQL, and I'm curious if it's possible to dynamically pull data from the database using JavaScript in Tit ...

Error: the specified item is not a valid function

As a newcomer to the world of JavaScript, I am eager to learn and explore new concepts. Currently, my focus is on centralizing the code for accessing my MySQL database within my Express JS server using promises. Below is an attempt I have made in achieving ...

Having issues with my JavaScript timer - seeking assistance in troubleshooting the problem

Trying to set a timer for my little game, but facing some difficulties. The timer causes the balance to randomly increase from 0 to 13000 + some extra amount. <script> var coins = 0; var speed = 1; </script> <center> <h4> ...

What is the best method to redirect users who are not logged in from every URL when using PassportJs?

I am currently developing a web application using NodeJS, and I have integrated PassportJS with passport-local-mongoose for authentication. Below is the code snippet I've created for the root route to verify if the user is logged in: app.get('/ ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Vue: utilizing shared methods in a JavaScript file

Currently, I am building a multipage website using Vue and I find myself needing the same methods for different views quite often. I came across a suggestion to use a shared .js file to achieve this. It works perfectly when my "test method" downloadModel i ...

Tips for resolving the "unsafe-eval" issue in Vue3 on the client-side platform

My app is built using Express, cors, and helmet. I have incorporated Vue3 on the client-side only, with the library file being self-hosted in the public folder. To add the module to the client-side, I simply include the following script: <script type=&q ...

What is the best way to fetch a partial JSON response object from an API using JavaScript?

Currently, I am utilizing the One Bus Away API, returning a response object in this format: { "code": 200, "currentTime": 1504150060044, "data": { "entry": { "arrivalsAndDepartures": [ {AnD_item1 ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

Avoid reloading the page when the form is submitted using form.trigger('submit') command

My current code functions properly when the user clicks on the form's submit button: // load dashboards when filter form is submitted $('div.active form.filter-form').submit(function (e) { // get subm ...

AngularJS is throwing an error because the term "grunt" has not

Today is the day I embark on my journey with Grunt for testing my JavaScript code. All the necessary grunt modules have been successfully installed and are documented in a json file called package.json. { "name": "LarissaCity", "private": true, ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

What are the advantages of polymer's inter-component data binding?

I am working on a login component and I want to ensure that the login status is accessible by other components within my application. Is there anyone who can share some functional code snippets or examples? I require a method for binding or event handlin ...