Should a react class that makes api call (a service) use static methods?
Eg:
class ProductService{
static getAllProducts(){ return fetch(...)}
static saveProduct(){ return fetch(...)}
...
}
Or should I create an instance eg. (new ProductService()).getAllProducts
Or Should I use a singleton pattern
I would rather use static methods because they are simpler and potentially faster. Also, it does not make sense to instantiate a class if there is no state specific to the instance.
Just put your functions for one service in a file my-service.js or my-service.ts and use:
import {myFunction} from "../services/my-service.js.
In reality, you will probably need to create custom hooks, so you can update React contexts or states. For example, to create a service with all your API calls to modify "products": "use-product.ts". This allows to organize your code in multiple services. It is the same way it is done in framework React like Next.js. Static is not a good solution because it will be hard to mock when testing.
Instances raise ESLint error: class-methods-use-this on most methods for a service without state. Singleton pattern seems to be more work, even if backend frameworks and Angular use this method, injecting the singletons.
Related
So I use angular services declared as public to keep the state of what the service controls between differents views in the service's variables.
Example:
View 1 to scan and connect to bluetooth devices.
View 2 (view 1 already destroyed): Show device information of bluetooth device connected(in view 1).
Im just starting with NextJS and I don't see any way in the documentation to import components like public service in angular.
I do have been researching and only things similar are ContextAPI and redux, to save maybe the components variables states like that. But it isn't quite like Angular services. Is there something like angular public services or I have to use manually contextapi/redux to save the information between components
Angular and React structures are quite different things, while angular uses MVC but react uses view-model so there isn't any original service-like concept in react like angular, but you can do it in your way. you can define some classes to handle things you want like angular services or even use state managing to handle this ...
hope this can give you sight.
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.
I have a service loaded into a component as a provider. This service may return data using Http or it may not, the component should not care. However, it seems that the component itself must include HTTP_PROVIDERS if the loaded service uses Http. This breaks separation of concerns. What am I misunderstanding?
This breaks separation of concerns. What am I misunderstanding?
In order to support instantiating multiple instances of a service (i.e., so all services don't have to be singletons), an Angular app needs a way to specify multiple injectors (not just one). These injectors need to be created and configured in some kind of hierarchy. The component/directive tree, since it is a tree, already has a hierarchy. So Angular uses the (existing) component tree to configure dependency injection. I like to think of it as a sparser "injector tree" that overlays the component tree.
I think it would be more work to define a separate hierarchy for services – we, as developers, would probably have to define and configure another injector tree of some sort.
So instead of thinking of it as "components need to know the dependencies of services" (which, when stated that way, it does sound like we're breaking separation of concerns), I like to think of it more like the following: "when I write an Angular app, I have to configure my providers/dependencies on the injector tree"... and since the injector tree overlays the component tree, I use components to configure it.
But this is not ideal, since if you want to reuse components in a different app, you might need to change the providers arrays (i.e., you may need to reconfigure the injector tree).
In fact, it's better to specify the HTTP_PROVIDERS when bootstrapping your application:
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
But I agree with you that there are some impacts on having configuration of providers only on components.
The previous configuration will work because of hierarchical injectors.
See this question for more details about hierarchical injectors:
What's the best way to inject one service into another in angular 2 (Beta)?
All:
I am pretty new to React from AngularJS. In AngularJS, there is service dependency inject which can provide a service instance to do data fetching, processing, etc., other than UI operation. I wonder how to do this(or implement that injection) in React component?
Thanks
I prefer to create a service in another file that exposes the 'public' functions through module.exports.
e.g.
module.exports = {
foo: function(){ return bar; }
}
which is then referenced by Components using
import myService from './routetoservice/myService'
An Extension to Michael Dunn's Answer
This is the actual answer ,
Service pattern is not limited to any programming language or
library.
We can implement this concept in any language , Even we can
implement this in react
A tiny service can be created on server OR in ui browser in Javascript that serves some logical purpose
It gives us benefits of code availability, code management , code isolation of particular logic
Its a very native way for code availability, code management , code isolation of particular logic
If we compare redux/flux vs services ,redux/flux also serve these purpose's
Currently i am using redux and its actions , and also created my tiny services on ui when required.
No need to use OTHER NPM MODULES FOR CREATING SERVICES , Just Michael Dunn's solution is enough
In reactjs we use the flux pattern to provide data handling. Here is an example of that with reflux. React with Flux: is this the dogmatic pattern or are there equal/better options?.
React seems philosophically opposed to services in the Angular sense, apparently preferring tight coupling of UI and logic.
But I have found a react-services module, which seems to offer what you are after:
• separate your component and application state by introducing a service layer that takes care of propagating changes through your application
• manage component dependencies in an explicit, testable way
• there's no events and no lifecycle management - everything is done automatically for you
• it's tiny and easy to understand - the core is less than 100 lines of code
https://medium.com/#alshdavid/react-state-and-services-edb95be48851
Here's an article showing how to do it with nothing but React Context and rxjs
What is better? Or maybe - is the following a good practice?
I use Spring.net to create an instance of DbContext and then inject it into every controller for use in actions. The object is a singleton. Sometimes I get an exception which says that the "The ObjectContext instance has been disposed.." I suspect that this might be the reason, however this is not repeatable, and so far my application is only used by me during the development.
Now, would it be better to create a DbContext in every controller class and reuse in it's actions; or maybe create the DbContext object in every action itself; or just set it in the Spring config not to be a singleton, so it is created every time it is being accessed?
It is best to inject your dbcontext using request scope. That way, the context is created on the start of a request and disposed at the end. During the request you'll have a db context available so that it can handle lazy loaded objects for you.
When you register as a singleton, the dbcontext is shared for all requests, which most of the time isn't what you want. For instance, it might be that it hold a reference to all your loaded objects, potentially loading the entire db into memory.