Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript rxjs在两个单独的步骤中(针对一个主题)进行管道和订阅,但未按预期工作_Typescript_Rxjs_Rxjs6 - Fatal编程技术网

Typescript rxjs在两个单独的步骤中(针对一个主题)进行管道和订阅,但未按预期工作

Typescript rxjs在两个单独的步骤中(针对一个主题)进行管道和订阅,但未按预期工作,typescript,rxjs,rxjs6,Typescript,Rxjs,Rxjs6,这让我头疼。。。以下代码按预期工作: const s$ = new Subject<any>(); s$.pipe( switchMap( x => { debugger; return myService.getSth(); } ) ).subscribe(x => { debugger; }); s$.next(); 我错过了什么?对可观察对象

这让我头疼。。。以下代码按预期工作:

const s$ = new Subject<any>();
  s$.pipe(
      switchMap(
        x => {
          debugger;
          return myService.getSth();
        }
      )
    ).subscribe(x => {
    debugger;
  });
  s$.next();

我错过了什么?

对可观察对象(包括主体)调用
.pipe
不会修改该可观察对象的功能,而是会生成一个新的可观察对象。在您的第一个示例中,您对新的可观察对象调用subscribe。在第二个示例中,您对新的可观察对象不做任何操作,然后订阅原始的未映射主题。如果没有任何东西引用新的可观察对象,它就丢失了

.pipe
的结果保存到变量中,然后订阅该变量:

const mapped$ = s$.pipe(
  switchMap(
    x => {
      debugger;
      return myService.getSth();
    }
  )
);

mapped$.subscribe(x => {
  debugger;
});

s$.next();

尴尬。。。当时没有完全了解管道的内部工作,谢谢。默认情况下,RxJS可观察对象是冷的,这正是您99%的时间都不想要的。
const mapped$ = s$.pipe(
  switchMap(
    x => {
      debugger;
      return myService.getSth();
    }
  )
);

mapped$.subscribe(x => {
  debugger;
});

s$.next();