[英]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.