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:

  1. vite:^ 2.6.4;
  2. rxjs:6.6.6;
  3. axios:^ 0.24.0;
  4. Vue3 + TS (Angular supports RxJs by default, Vue does not configure RxJs by default, so it is more appropriate to create class operators);
  5. Source: JSONPlaceholder.

Create operator:

  1. 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:

  1. zip:
    1. Features: pull chain combination (one to one combination);
    2. Purpose: To store the results of two interfaces in an array in merge order.

Filter operator:

  1. filter: Checks whether the data is returned normally, using arrays duringeveryThe function ensures that each interface is in a 200 state.

Conversion operators:

  1. Map: Only business-related data content is returned from the huge data returned by the interface.

Implementation process:

  1. Import dependencies:
import axios from 'axios'
import { from, zip } from 'rxjs';
import { filter, map } from 'rxjs/operators';
Copy the code
  1. 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
  1. Define the receiving object:
let response = null;
Copy the code
  1. 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
  1. 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.