This is the 8th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.
Dear, hello, everyone. I am “Front-end Xiaoxin”. 😇 has been engaged in front-end development and Android development for a long time
Experimental objectives:
To combine data from different interfaces into a single field.
Environment and Dependencies:
- vite:
^ 2.6.4
; - rxjs:
6.6.6
; - axios:
^ 0.24.0
; - Vue3 + TS (Angular supports RxJs by default, Vue does not configure RxJs by default, so it is more appropriate to create class operators);
- Source: JSONPlaceholder.
Create operator:
- From: The core operation. Reactive programming is impossible without an Observable. The FROM operator converts promises (like Observables) returned by the interface into Observables.
Merge operator:
- zip:
- Features: pull chain combination (one to one combination);
- Purpose: To store the results of two interfaces in an array in merge order.
Filter operator:
- filter: Checks whether the data is returned normally, using arrays during
every
The function ensures that each interface is in a 200 state.
Conversion operators:
- Map: Only business-related data content is returned from the huge data returned by the interface.
Implementation process:
- Import dependencies:
import axios from 'axios'
import { from, zip } from 'rxjs';
import { filter, map } from 'rxjs/operators';
Copy the code
- Transform the promise returned by the interface into an Observable:
const observable1 = from(axios.get('https://jsonplaceholder.typicode.com/todos/1'));
const observable2 = from(axios.get('https://jsonplaceholder.typicode.com/posts/1/comments'));
Copy the code
- Define the receiving object:
let response = null;
Copy the code
- Data processing via Rxjs related operators:
// Merge two Observables
zip(observable1, observable2)
/ / pretreatment
.pipe(
// Filter data: The status of all interfaces must be 200
filter(res= > res.every(res= > res.status === 200)),
// Only business data is returned for use
map(res= > res.map(res= > res.data)),
).subscribe(res= > {
// Merge the data from the two requests into the Response objectresponse = { ... res[0].comments: res[1],}console.log(response);
})
Copy the code
- Merge result display:
{
"userId": 1."id": 1."title": ""."completed": false."comments": [{"postId": 1."id": 1."name": ""."email": ""."body": ""}}]Copy the code
Welcome to follow my public account “Front-end Xiaoxin students”, the first time to push original technical articles.