主题需要 RxJS6 asObservable() 吗? [英] RxJS6 asObservable() needed on a Subject?

查看:45
本文介绍了主题需要 RxJS6 asObservable() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候需要在主题(例如 BehaviorSubject)上使用 asObservable() 来获取主题的可观察性?主体本身也可以转换为 Observable.

When is asObservable() needed on a Subject (e.g. BehaviorSubject) to get a observable of the subject? The subject isself can be casted to an Observable as well.

  1. name1$name2$ 之间的技术区别是什么?
  2. 应该使用哪个(name1$name2$)?
  1. What are the technical differences between name1$ and name2$?
  2. Which one should be used (name1$ or name2$)?

代码示例

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs';

export class Person {
  private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');

  public get name1$(): Observable<string> {
    return this.nameSubject.asObservable();
  }

  public get name2$(): Observable<string> {
    return this.nameSubject;
  }

  public setName(value: string): void {
    this.nameSubject.next(value);
  }
}

提前感谢您的回答!

推荐答案

一般情况下,只有在 JavaScript 中使用 RxJS 时,才推荐使用 asObservable().使用 TypeScript,你可以只使用类型转换,它不会让你调用 next() 等等.

In general, it's recommended to use asObservable() only when using RxJS in JavaScript. With TypeScript you can use just type casting and it won't let you call next() and so on.

private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');
public nameSubject$: Observable<string> = this.nameSubject;

这是官方推荐的在 TypeScript 中将 Subjects 转换为 Observables 的方式.
详情参见 https://github.com/ReactiveX/rxjs/pull/2408#issuecomment-282077506.

This is the officially recommended way of turning Subjects to Observables in TypeScript.
For details see https://github.com/ReactiveX/rxjs/pull/2408#issuecomment-282077506.

这篇关于主题需要 RxJS6 asObservable() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆