如何为对象创建行为主题并在另一个组件上订阅它?

Pra*_*esh 4 object rxjs typescript behaviorsubject angular

我在服务类中创建了一个行为主题.

    public personObject: BehaviorSubject<any> = new BehaviorSubject<any>({
                                               personId: 1,
                                               name: 'john doe'
                                               });
Run Code Online (Sandbox Code Playgroud)

在导入此服务的组件上,我已订阅此行为主题,如下所示:

`        this._subscription.add(
            this._bankService.personObject.subscribe(data => {
                this.personObject = data;
                console.log(data);
            })
        );`
Run Code Online (Sandbox Code Playgroud)

但我无法在行为主题中获得准确的数据集.请帮忙.

编辑 我忘了提到我已经使用ViewContainerRef来创建我的兄弟组合.所以我添加了一个答案,对我的问题几点评论.

Dmi*_*nko 6

服务

@Injectable()
export class DataService {

  private _dataListSource: BehaviorSubject<IData[]> = new BehaviorSubject([]);
  dataList: Observable<IData[]> = this._dataListSource.asObservable().distinctUntilChanged();

  ...

  getDataList(): Observable<any> {
      return this.httpService.get('/data').map(res => {
          this._dataListSource.next(res);
      });
  }
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的组件中使用它

export class DataComponent implements OnInit {

    public dataList$: Observable<IData[]>;

    constructor(public dataService: DataService) {}

    ngOnInit() {
        this.dataList$ = this.dataService.dataList;
        this.dataService.getDataList().subscribe();
    }
}
Run Code Online (Sandbox Code Playgroud)

和你的HTML

    <div *ngIf="dataList$ | async; let dataList; ">
        <div *ngFor="let data of dataList">
            {{ data | json}}
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

  • @Sledge 我的团队在变量末尾使用 $ 来强调它是可观察的。对我们来说很舒服。您可以使用任何您想要的名称。 (2认同)

Pra*_*esh 1

我忘了提及,我正在使用 ViewContainerRef 创建同级组件,结果发现行为主体与使用 ViewContainerRef 创建的组件的工作方式不同。

其他方面,任何对象的行为主体的工作方式与数字或字符串完全相同。我现在使用 @Input 将数据发送到组件。