angular - 为什么在使用 switchMap 将 route.parame 与 http.get 进行管道传输时可观察链不会终止

angular - why observable chain doesn't terminate when piping a route.parame with a http.get using switchMap

为什么第一个链没有完成?

switchMap 应该取消订阅以前的可观察对象,因为 http.get 是一次性可观察对象,我认为它会记录完整。

相反,我一直得到 http.get 结果。这就是我对 flatMap 的期望。

    this.route.params
        .pipe(
            switchMap(params => {
                return this.http.get('assets/data/module.json');
            })
        )

        .subscribe(
            res => {
                console.log(res);
            },
            e => e,
            () => console.log('complete')
        );

默认 http.get 结果完整。

    this.http.get('assets/data/module.json').subscribe(
        res => {
            console.log(res);
        },
        e => e,
        () => console.log('complete')
    );

我认为您弄错了 switchMap 应该做什么。如果发出新参数,switchMap 将取消订阅内部可观察对象(您的 http.get 调用)。一旦您的 http.get 通话结束,它不会取消订阅参数。

您想要的是在管道中的 switchMap 运算符之前添加 first() 运算符。此外,您可能希望使用 mergeMap 而不是 switchMap,但在您的情况下应该无关紧要。

this.route.params
    .pipe(
        first(),
        switchMap(params => {
            return this.http.get('assets/data/module.json');
        })
    )

    .subscribe(
        res => {
            console.log(res);
        },
        e => e,
        () => console.log('complete')
    );

这将采用 route.params 发出的第一个参数,发出您的 http 请求,然后完成 observable。

可以使用switchmap的示例: 假设我们有一个搜索字段,我可以在其中输入任何内容。当我在搜索字段中输入内容时,angular 将调用后端来检索搜索结果。现在我可能会更改我的搜索词,而最后一个搜索请求仍处于待处理状态。在这种情况下,switchMap 将取消旧的 get 请求并发出新的。