'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.
Solution 1:[1]
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
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
<div *ngIf="dataList$ | async; let dataList; ">
<div *ngFor="let data of dataList">
{{ data | json}}
</div>
</div>
Solution 2:[2]
In the component where you subscribe to 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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Roman Bondar |
