Ionic/angular provider/service - singleton - single instance? - angularjs

I have read that service(angular)/provider(ionic) can be specific to components, or can be shared by components by registering it at module level. I understand that this is singleton concept that is single instance shared by all components. My question is - suppose the service/provider has code that fetches data from db based on logged in userid, then in this case, how does a single instance concept differentiate between all users using the app? Bit confused on this aspect.

As far As i know singleton means a single component/service that have content that can be shared with any other page/component/controller/...
but all that is happening in one instance of the app.
Example:
lets say in our project we have 3 pages with controllers: page1.html, ctrl1.js, page2.html, ctrl2.js, page3.html, ctrl3.js
We also have 1 service: service1.js
In service1.js we have a function called getUserName()
The concept of singleton will allow getUserName() to be called from all 3 controllers. if the service is not sigleton this means it will be related to one controller/page, so if service1.js is only related to ctrl1.js, the function getUserName() cannot be called from ctrl2.js
Important: all this is happening in one instance of the app, singleton does not mean that the service is SHARED between all running instances of the app.
That being said, if you are using your service to get data from the database based on some parameters, it is the logic you implemented that decide what data will be returned.

Related

In angular how do i share data on a session basis

So my understanding is that factories are singletons so any stateful data for a session would be ill placed here.
My next point of call was a service which returns a new instance of the service when injected however I am unsure how I would share one instance of the service to multiple controllers.
Is this an accepted way to solve this issue or does angular provide a better way?
My current use case is that I have a view with some partial views (each partial has it's own controller) and a modal window which takes in a row id and will display data dependant on that data.
I need to be able to share a instance of the service (or equivalent) across these controllers but on a per session basis.
How is this best done?
The singleton exists for one user and loaded SPA. Thats what you would usually refer to as a session. Its a good place to store data that needs to be accessed by different controllers.

Why are angular services Singletons?

I am trying to understand singleton pattern.
I write a lot of code in angular and recently I wanted to refactor some of my code and move it to a common place which can be shared by different controllers.So I moved all common utils to my services.
Now the documentation over here says that angular services are singletons but I want to understand the reason behind having singleton pattern here ? Why not have multiple instances of the service object instead of passing references to controllers ?
It all falls in the name "Service". Service, acts like a medium to communicate between controllers or even directives for that matter. Not only for communication, you can add a set of utility functions in your service, which can be used throughout the module/app. This does not need to have multiple instances to serve the purpose. Hence, singleton.
Angular services are the recommended way to exchange data and communicate between controllers. In order therefore to allow this data exchange, services are singleton objects which means that you are guaranteed to have the same service reference between all your controllers.
As an example, imagine that you have an Angular application that displays a list of messages received from another user in the center of the page, as well as the number of received messages or new message notifications in the header. The header and the page content will most probably be under different scopes and be handled by different controllers. In order for these two controllers to have the same view of messages received and be able to display them consistently they will need to use a singleton object holding this information. This object is an Angular service.

AngularJS inject a singleton per view service

I am trying to negotiate a conceptual issue in AngularJS.
I have a controller that is currently using multiple services. Among this services, a few are used as a singleton per view. This means that once I enter a certain view (actually state since I am using Ui-Router), these specific services, which have some dependencies among themselves, are singleton(s).
However, when exiting this view and going later going back should instantiate new instances of them (and again being singletons for this state).
There are a few possible solution I came out with, all of them are not great:
Manually force instantiating them every time entering this view.
Manually force deleting from cache every time exiting this view.
Using a controller rather then using service/factory/provider.
Creating my own "factory" type, which will be implementing the angular's injection without being a singleton.
I was wondering if angular can offer some sort of "type" (such as non-singleton factory), that can solve this issue.

AngularJS data model architecture approach

I'm new to AngularJS and having a hard time wrapping my head around the conceptual model.
Let's say I want to have an object hierarchy to model a stash repository: Projects contain Repositories contain Tags. Do I create one app, one module and multiple controllers? (Can a module have multiple controllers?) Separate app per object type? Separate module per object type?
All the various data types will be populated by making REST API queries. Read-only for now. Does that change things?
Also, why are they called controllers? They seem to be models. As far as I can tell the controller is actually the AngularJS plumbing.
Here is my rather simple explanation:
A module is just simply a container for all the bits and pieces of your app (services, controllers, directives, filters etc).
Your application may contain different modules - some that you wrote and other third party ones, such as ngGrid for example.
You define a module like this:
var myAppModule = angular.module('myApp', []);
A controller is where the business logic of your application resides. The controller may handle the model, but it is not the model.
The AngularJS documentation for controllers states:
Use controllers to:
Set up the initial state of the $scope object. Add behavior to the
$scope object.
I break up my controllers in to the logical functions that they are supposed to handle. For example, I've written an app to help with combat tracking in a tabletop RPG. I have a controller that handles martial combat and another that handles magick. I also have another controller that helps with the characters. All these controllers are part of my combat app.
I only have one service that is responsible for querying a REST API to retrieve stats and results from a database.
The AngularJS documentation has improved a lot recently and I would recommend reading through it to give you a rough idea of how things work together!
In your example, I'd have a separate controller for each of Projects, Repositories and Tags. I'd have a service to query your datatypes. These would be grouped as part of one module/app.

Don't understand the need for $cacheFactory if Factories are singletons

I'm relatively new to AngularJs and I'm trying to build a single page application with it. My application runs within a content management site. I have 3 factories for user, group and site functions.
I'm interested in using angular's $cacheFactory but I'm not sure what the benefit is if my data remains in the factory since it's a singleton.
For example, my user factory has an object called allUsers. This object is used through my application for different views. Intuitively, it seems like it's something that should be cached but I'm having a hard time understanding why since this object is in the user factory which can be access from any of my controllers.
CacheFactory is a factory:
The purpose of the Factory Method pattern is to define an interface for creating an object but deferring instantiation of the object to subclasses.
which creates new instances each time an object of its type is created, unlike a Singleton:
The intent of the Singleton pattern is to ensure that only one instance of a class is loaded, and that the instance provides a global point of access.
In Angular, the CacheFactory offers the following benefits over other solutions:
Caches can be injected into a filter, unlike controller scopes
Caches can be enumerated
Caches can be easily destroyed or redefined
Caches are not tied to digest data binding, unlike controller scopes
Caches are not tied to browser permissions, unlike cookies or localStorage/sessionStorage
I'm not sure what the benefit is if my data remains in the factory
CacheFactory offers the following features:
'should create cache with defined capacity'
'should blow away the entire cache via removeAll and start evicting when full'
'should correctly refresh and evict items if operations are chained'
But CacheFactory also has the following unexpected behaviors:
'should purge the next entry if the stalest one was removed'
'should only decrement size when an element is actually removed via remove'
References
Deep dive into JSF patterns
Factory method and MVC
AngularJS Source: cacheFactorySpec.js
Why is OOP Difficult?
DCOM and CORBA Side by Side, Step By Step, and Layer by Layer

Resources