E
E
enotiik2022-01-23 23:43:11
Angular
enotiik, 2022-01-23 23:43:11

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

Second element code:
export class SecondcomponentComponent implements OnInit {
  
  posts!: Post[];
  constructor(
    private service: ExampleService,
  ) { }

  ngOnInit(): void {
    this.service.pubs.subscribe(p => this.posts = p);
  }
  
}

And there is a service:
export class ExampleService {

  pubs: BehaviorSubject<Post[]> = new BehaviorSubject<Post[]> (Posts);
  constructor() { }
  
}

How to correctly add a new element to the array so that it (the array) is updated on both components?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lan_ser, 2022-01-25
@Lan_ser

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 question

Ask a Question

731 491 924 answers to any question