Services are a great way to share information among classes that don't know each other. by using services you'll be able to
fetch data form any component in your app
use Rxjs operators and others.....
use it as State management ( using subjects)
and have a clean and beautiful code
why Rxjs
RxJS can be used with any frameworks or Pure Javascripta .
that's mean the following code works on Vue.js or vanilla
RxJS is a library for composing asynchronous and event-based programs by using observable sequences
RxJS offers a huge collection of operators in mathematical, transformation, filtering, utility, conditional, error handling, join categories that makes life easy when used with reactive programming.
3. How to Create Service in React or Vue
install the following library's
$ npm install axios rxjs axios-observable
create a folder to contain all of your api services, usually i name it services
and I also create it in src/srvices, it doesn't matter create it where every you want.
create new .ts or .js file, i'll name it task.ts (because am using typescript here)
Use axios in a rxjs way. use Observable instead of Promise
axios-observable
Observable (as opposed to Promise) based HTTP client for the browser and node.js
Want to use axios in a rxjs (observable) way? There we go!
This API of axios-observable is almost same as API of axios, giving you smooth transition. So the documentation mirrors the one of axios (A few exceptions will be cleared pointed out).
Using npm:
note: axios and rxjs are peer dependencies.
$ npm install axios rxjs axios-observable
Example
Performing a GET request
importAxiosfrom'axios-observable';// or const Axios = require('axios-observable').Axios;// Make a request for a user with a given IDAxios.get('/user?ID=12345').