简体   繁体   English

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

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

I created a behaviour subject in a service class.我在服务类中创建了一个行为主题。

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

On a component that imports this service, i subscribed this behaviour subject like this:在导入此服务的组件上,我订阅了此行为主题,如下所示:

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

But I am not able to get exact dataset in the behaviour subject.但我无法在行为主题中获得准确的数据集。

Edit I forgot to mention that I used ViewContainerRef to create my sibling component which I added to an answer with a few comments.编辑我忘了提到我使用 ViewContainerRef 创建了我的兄弟组件,我将其添加到带有一些评论的答案中。

Service服务

@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 file 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 file HTML 文件

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

I forgot to mention that I was using I was using ViewContainerRef to create a sibling component and it turns out behavior subject does not work the same way with component created using ViewContainerRef.我忘了提到我正在使用 ViewContainerRef 创建同级组件,结果发现行为主题与使用 ViewContainerRef 创建的组件的工作方式不同。

Other wise Behaviour subjects of any object work exactly like with number or string.其他明智的任何对象的行为主题都与数字或字符串完全一样。 I used @Input to send data to component for now.我现在使用@Input 将数据发送到组件。

In the component where you subscribe to personObject :在您订阅personObject的组件中:

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

constructor(private _storeService: StoreService) {}

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

in the component where you change object properties:在您更改对象属性的组件中:

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.

相关问题 如何使用 Observable 订阅行为主体 - How to Subscribe a Behavior Subject with an Observable 主题订阅未在组件中触发 - Subject subscribe is not triggering in a component 试图在服务中创建可观察对象,在组件中使用它,在另一个组件中订阅它,角度为4 - trying to create an observable in a service, use it in a component and the subscribe it in another component angular 4 如何在条件 ViewChild 上订阅主题? - How to subscribe to a Subject on a conditional ViewChild? Angular,行为主体,在一个组件中更改数据,在另一个组件中进行更改 - Angular, behavior subject, change data in one component, make changes in another component 带有类对象的 Angular 7 行为主体 - Angular 7 behavior subject with class object 当我进入另一个组件的Subject调用的subscribe方法(角度为2/4/5)时,为什么在控制台中看不到我的根变量组件? - Why I can't see my root variable component in the console when I'm into subscribe method of Subject call by another component (angular 2/4/5)? 订阅 websocket 主题创建多个连接 - subscribe to websocket subject create multiple connections 在基类中订阅行为主题时,Rxjs订阅不起作用 - Rxjs subscribe not working when subscribing to Behavior Subject in base class rxjs行为主题从组件设置值 - rxjs behavior subject set value from component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM