Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A QuizGeneral Tech Bugs & Fixes 3 years ago
User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.
For me the revelation came when I realise that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through Dependency Injection.
Say we have:
app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);
The difference between the three is that:
a's stored value comes from running fn , in other words: fn()b’s stored value comes from newing fn, in other words: new fn()c’s stored value comes from first getting an instance by newing fn, and then running a $getmethod of the instancewhich means, there’s something like a cache object inside angular, whose value of each injection is only assigned once, when they've been injected the first time, and where:
cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()
This is why we use this in services, and define a this.$get in providers.
No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
manpreet
Best Answer
3 years ago
As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using
thisand not returning anything.I was under the assumption that a service was always a singleton, and that a new factory objectgets injected in every controller. However, as it turns out, a factory object is a singleton too?
Example code to demonstrate:
When changing
user.firstinACtrlit turns out thatuser.firstinBCtrlis also changed, e.g.Useris a singleton?My assumption was that a new instance was injected in a controller with a factory?