The source code:
import { of } from 'rxjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
@Injectable(a)export class JerrySandBoxService{
name = 'Jerry';
print(){
const observable = of(1.2.3);
const opt = map(num= > 'hello world: ' + num + ' done');
const newObservable = opt(observable);
newObservable.subscribe(data= > console.log(data)); }}Copy the code
Execution Result:
The map operator receives an arrow function:
Internal implementation of map: Returns a new function named mapOperation that takes a single argument.
Now execute the opt operation:
The source is Observable, and the project is the arrow function specified by the application developer:
Constructor for the Map operator:
Create an Observable and pass the current Observable to the source, operator.project (arrow) function:
Subscribe to the new Observable:
Note the syntax: assign the operator object contained in this to the operator variable in braces:
Sink is subscriber, source is Observable, and operator is arrow function:
If there is an operator, execute the arrow function first:
Pass the result returned by the arrow function as the new input parameter to the subscriber next method:
Finally execute the arrow function passed in when we call SUBSCRIBE:
Let’s look at another example: using Map to gracefully consume an API:
const http$ : Observable<Course[]> = this.http.get('/api/courses');
http$
.pipe(
tap(() = > console.log('HTTP request executed')),
map(res= > Object.values(res['payload']))
)
.subscribe(
courses= > console.log("courses", courses)
);
Copy the code
For more of Jerry’s original articles, please follow the public account “Wang Zixi “: