代码之家  ›  专栏  ›  技术社区  ›  papiro

我如何向rxjs主体发出可观察到的值?

  •  2
  • papiro  · 技术社区  · 6 年前

    我想提供一个rxjs Subject next HttpClient get 打电话。我就是不太明白。我想知道为什么下面的结果导致subscribe处理程序没有被调用:

    -查看

    export default abstract class TileView implements OnInit {
      constructor (private configService : ConfigService) {}
      ngOnInit () {
        this.configService.fetch(this.type()).subscribe( res => {
          console.log(res)
        }); 
      }
    }
    

    export class ConfigService {
      public subject = new AsyncSubject();
    
      constructor (private http : HttpClient) {}
    
      fetch (type) {
        this.http.get(
          api.host + api.base + interpolate(api.config, { type }) + "/"
        ).subscribe( res => {
          this.subject.next(res);
        });
    
        return this.subject;
      }
    }
    

    有没有任何方法可以返回主题,并用一个方法调用触发http调用?这很奇怪,因为返回了主题,注册了订户,http调用完成并 this.subject.next(res)

    4 回复  |  直到 6 年前
        1
  •  1
  •   Rafael    6 年前

    皮埃尔,发生这种事的原因是 完成 Subject.prototype.complete()

    在您的示例中,您可能希望为订阅者使用BehaviorSubject,它将为订阅者发出流中的最后一个值,而不管完成情况如何:

    AsyncSubject发出发出的最后一个值(并且只有最后一个值) 由可观察到的源,并且只有在该源可观察到之后 完成(如果源Observable没有发出任何值 AsyncSubject也会在不发出任何值的情况下完成。)

    Subject Documentation

    如果由于初始值传播而不愿意使用BehaviorSubject,请使用ReplaySubject(1)。

        2
  •  1
  •   Pratap A.K    6 年前

    完成可观察的,它就会工作

    fetch (type) {
        this.http.get(
          api.host + api.base + interpolate(api.config, { type }) + "/"
        ).subscribe( res => {
          this.subject.next(res);
          this.subject.complete();
        });
    
        return this.subject;
      }
    

    另一种方法是使用behaviorSubject,在这种情况下,您需要处理null检查,因为behaviorSubject需要默认值

    public behaviourSub = new BehaviorSubject(null);
    
    this.configService.fetch(this.type()).subscribe( res => {
        if (res !== null) {
          // actual value emitted
        }
    });
    
        3
  •  1
  •   xrobert35    6 年前

    AsyncObservable的一个特殊性是他等待 完成() “在发送信息之前完成

    因为AsyncSubject扩展了Observable,所以没有必要,但我建议您使用“ 返回this.subject.asObservable() 行为主体 例如,不需要更改代码;)

        4
  •  0
  •   Learning    6 年前

    订阅视图中的“主题”以不获取。也不需要从你的服务中返回主题。

    export default abstract class TileView implements OnInit {
      constructor (private configService : ConfigService) {}
      ngOnInit () {
        this.configService.subjectChanged(this.type()).subscribe( res => {
          console.log(res)
        }); 
      }
    }
    

    服务: 导出类配置服务{

      public subjectChanged = new Subject();
    
      constructor (private http : HttpClient) {}
    
      fetch (type) {
        this.http.get(
          api.host + api.base + interpolate(api.config, { type }) + "/"
        ).subscribe( res => {
          this.subjectChanged.next(res);
        });
      }
    }
    
    推荐文章