Angular6 为什么switchmap返回http响应,而map返回可观察响应
在本例中,switchMap给出http响应,但当使用map时,返回一个可观察的。我相信这与switchMap的“扁平化”有关,但仍然不理解switchMap在幕后是如何产生http响应结果的Angular6 为什么switchmap返回http响应,而map返回可观察响应,angular6,rxjs6,Angular6,Rxjs6,在本例中,switchMap给出http响应,但当使用map时,返回一个可观察的。我相信这与switchMap的“扁平化”有关,但仍然不理解switchMap在幕后是如何产生http响应结果的 import{Component, OnInit} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import { of, from, Observable, forkJoin } from 'rxjs'; i
import{Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { of, from, Observable, forkJoin } from 'rxjs';
import { map, mergeMap, switchMap, tap, flatMap} from 'rxjs/operators';
@Component({
selector: 'star-wars',
template: ``,
})
export class StarWars {
private peopleUrl = 'https://swapi.co/api/people/';
constructor(private http: HttpClient) {}
ngOnInit() {
of(1)
.pipe(
map(() => this.http.get('https://swapi.co/api/people/1')),
// produces Observable {_isScalar: false, source: {…}
switchMap(() => this.http.get('https://swapi.co/api/people/1')),
// produces http response {name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond"…}
)
.subscribe(res => {
console.log(res)
})
}
}
请澄清switchMap在这里做了什么来产生这种不同的结果,我们将不胜感激。可见光中的“展平”与您可能已经熟悉的展平阵列的概念类似 例如:
[[0], [1, 2], [3]].flatten()
// output [0, 1, 2, 3]
通常,展平意味着获取类型的值(例如,值数组的数组)并生成返回类型的值(例如,值数组)
类型类型有时称为高阶类型(例如,高阶函数是函数返回函数,高阶可观测值是可观测值的可观测值)。所以展平会将高阶类型转换为一阶类型
用TypeScriptflatte
编写的函数具有以下签名:
flatten(source: Type<Type<Value>>): Type<Value>
map
和flatten
的组合通常被称为flatMap
,虽然名称可能不同,但主要概念是相同的-将映射和展平作为一个动作
在数组上下文中,而不是:
[0, 1, 2, 3].map(x => Array(x).fill(x)).flatten()
// [[], [1], [2, 2], [3, 3, 3]].flatten()
// output: [1, 2, 2, 3, 3, 3]
我们可以使用:
[0, 1, 2, 3].flatMap(x => Array(x).fill(x))
RxJS有相当多的操作符充当平面图:
-正在同时展平可观测值,因此输入值和输出值可能具有不同的顺序mergeMap
-一次一个连续展平观测值,因此输入值和输出值的顺序相同concatMap
-展平可观察值,但仅提供最新值switchMap
flatMap
类操作符只需调用subscribe
即可从映射函数返回可观察对象,并为我们管理底层订阅
[0, 1, 2, 3].flatMap(x => Array(x).fill(x))