繁体   English   中英

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

[英]How to create behavior subject for object and subscribe to it on another component?

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

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

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

this._subscription.add(
    this._bankService.personObject.subscribe(data => {
        this.personObject = data;
        console.log(data);
    })
);

但我无法在行为主题中获得准确的数据集。

编辑我忘了提到我使用 ViewContainerRef 创建了我的兄弟组件,我将其添加到带有一些评论的答案中。

服务

@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);
      });
  }
}

TS文件

export class DataComponent implements OnInit {

    public dataList$: Observable<IData[]>;

    constructor(public dataService: DataService) {}

    ngOnInit() {
        this.dataList$ = this.dataService.dataList;
        this.dataService.getDataList().subscribe();
    }
}

HTML 文件

<div *ngIf="dataList$ | async; let dataList; ">
    <div *ngFor="let data of dataList">
        {{ data | json}}
    </div>
</div>

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

其他明智的任何对象的行为主题都与数字或字符串完全一样。 我现在使用@Input 将数据发送到组件。

在您订阅personObject的组件中:

import { StoreService } from '../../services/store.service'; // service file with personObject variable

constructor(private _storeService: StoreService) {}

this._storeService.personObject.subscribe( value => {
  console.log(value);
} );

在您更改对象属性的组件中:

import { StoreService } from '../../services/store.service';

constructor(private _storeService: StoreService) {}

ngOnInit(): void {
    let person = { personId: 0, name: '' };
    this._storeService.personObject.subscribe( value => {
      person.personId = value.personId; // set value personId from service
    } );
    this._storeService.order.next({...person, name: 'somebody'  } ); // set new value for name property
  }

暂无
暂无

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

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