简体   繁体   English

rxjs Observable .map没有执行

[英]rxjs Observable .map not executing

I have the following code that returns an observable, it checks if the this.data is valid JSON, otherwise it tries to fetch it from url. 我有以下代码返回一个observable,它检查this.data是否是有效的JSON,否则它会尝试从url中获取它。 The fetching and everything works. 提取和一切正常。

load():Observable<IStandardListOutput[]> {

return Observable.create(observer => {

  if (this.needsFetch) {
    var data;
    this.http.get(this.data)
      .map(res => {
        var result = res.text();
        // console.log(result);
        try {
          data = JSON.parse(result)
        } catch (e) {
          return Observable.of([{error:"ERROR LOADING JSON: " + this.data}]);
        }
        return data;
      }).subscribe(res => {
        observer.next(this._parse(res));
        observer.complete();
      });
  }else {
    observer.next(this._parse(this.data));
    observer.complete();
  }
});

} }

Now in the map/subscribe portion of the observer I have the following: 现在在观察者的map / subscribe部分中,我有以下内容:

let observable$ = this.loader.load(); // <-- load method above
observable$.map(res => {
  console.warn ("IN MAP: " + JSON.stringify(res));
});

observable$.subscribe(res=> {
    console.log("IN SUB: " + JSON.stringify(res));
  },
  err => {
    console.log(JSON.stringify(err))
  },
  () => {
    console.info("COMPLETE")
  }
);

What I see in the output/console is only the "IN SUB" (subscribe) function and a "COMPLETE". 我在输出/控制台中看到的只是“IN SUB”(订阅)功能和“COMPLETE”。 The console.warn in the .map function is never executed. 从不执行.map函数中的console.warn。

Any help is highly appreciated, thanks in advance 任何帮助都非常感谢,提前感谢

The map is never executed because it creates an observable that stays cold (no subscription). 永远不会执行映射,因为它会创建一个保持冷(无订阅)的可观察对象。 Add an empty subscribe() and it should work. 添加一个空的subscribe() ,它应该工作。

observable$.map(res => {
  console.warn ("IN MAP: " + JSON.stringify(res));
}).subscribe();

And another tip on rxjs debugging, if you want to peek into the value, you can always use the do operator (instead of your map ). 关于rxjs调试的另一个提示,如果你想查看值,你可以随时使用do运算符(而不是你的map )。

observable$
  .do((v) => console.log('debug point: ', v)) // <-- this is the addition.
  .subscribe(...your original handlers go here ...)

rxjs changed a lot. rxjs改变了很多。 Angular 2 (8) is very different from AngularJS. Angular 2(8)与AngularJS非常不同。

Since version 6 from rxjs, you need to import it with 从rxjs版本6开始,您需要将其导入

import {map} from 'rxjs/operators';

and, in your code, include it with a pipe , for example: 并且,在您的代码中,将其包含在pipe ,例如:

observable.pipe(map(res => res.json()).subscribe( {
console.log("IN SUB: " + JSON.stringify(res)); },
  err => {
    console.log(JSON.stringify(err))},
  () => {
    console.info("COMPLETE")
  }

hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM