Answer the question
In order to leave comments, you need to log in
How to change array in BehaviourSubject?
There are two components. The task of the first is to display the array and add elements to it (by pressing the button), the second should simply display this array.
First component code:
export class MainComponent implements OnInit {
posts!: Post[];
constructor(
private service: ExampleService,
) { }
ngOnInit(): void {
this.service.pubs.subscribe(p => this.posts = p);
}
add(): void {//привязаная к кнопке
const npost: Post = {id: 10, text: 'hello'};
this.service.pubs.pipe(map( p => p.unshift(npost)));
}
export class SecondcomponentComponent implements OnInit {
posts!: Post[];
constructor(
private service: ExampleService,
) { }
ngOnInit(): void {
this.service.pubs.subscribe(p => this.posts = p);
}
}
export class ExampleService {
pubs: BehaviorSubject<Post[]> = new BehaviorSubject<Post[]> (Posts);
constructor() { }
}
Answer the question
In order to leave comments, you need to log in
In
private postSource service: BehaviorSubject= new BehaviorSubject(Posts)
newPost = this.postSource.asObservable(); - the method will return an object with event subscription methods.
create method
emitNewPost(el: number) {
// add logic to add element to array
this.postSource.next(post ) - notify all subscribed components
}
in first component
add(){
this.server.emitNewPost(post) - call emitNewTask, pass data
}
to second
this.service.pubs.subscribe(p => this.posts = p);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question