Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provider 'xx' must return a value from $get factory method in AngularJs

I have written an angularjs factory as below

module.factory('LogService', function () {      function log(msg) {         console.log("Rahkaran:" + new Date() + "::" + msg);     }      return      {         log: log     };  }); 

But I kept getting this error

Provider 'LogService' must return a value from $get factory method

I googled about the error and I couldn't find any solution.

Coincidentally I changed the return statement to this

return{     log: log }; 

And error is gone!!

Is there any differences between having { in front of return or at the next line?

like image 350
Reza Avatar asked Jan 02 '15 07:01

Reza


People also ask

What is the use of factory in AngularJS?

AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function which allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application.

What is the return value of this function in AngularJS?

The return value of this function is the service instance created by this recipe. Note: All services in AngularJS are singletons. That means that the injector uses each recipe at most once to create the object. The injector then caches the reference for all future needs.

What is the use of provider in angular?

The Provider also tells the Angular Injector how to create the instance of dependency. There are four ways by which you can create the dependency: They are Class Provider (useClass), Value Provider (useValue ), Factory Provider ( useFactory ), and Aliased Class Provider ( useExisting).

How do I create a service in AngularJS?

AngularJS provides you three ways : service, factory and provider to create a service. A factory is a simple function which allows you to add some logic before creating the object. It returns the created object.


1 Answers

This is called Automatic semicolon insertion

The return statement is affected by automatic semicolon insertion (ASI). There is no line terminator ; between the return keyword and the expression allowed.

return a + b;  // is transformed by ASI into  return;  a + b; 

So you must insert { in front of return and Not at the next line.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

like image 116
Naeem Shaikh Avatar answered Oct 08 '22 15:10

Naeem Shaikh