javascriptangulartypescriptrxjsformbuilder

How can I get last of id value in Observable?


I have an Observable data like:

{ name: Jack, id: 1}
{ name: Albert, id: 2},
{ name: Johnny, id: 3}

I want to add the next data to this, but I must read the last of the id (in this case 3) value.

I try to do this:

id$ = this.comapniesService.getCompaniesInfos().pipe(
   map(res =>
     res.map(res => {
       return res.company_id;
     })
   )
 );

id2 = [];
  id = this.id$.subscribe(res => {
    return this.id2.push(res);
  });

and I have to get on HTML correct array:

<pre>
  {{ id2 }} //Display [1, 2, 3]
</pre>

but I try to add this to form builder like:

private buildForm() {
    this.form = this.formBuilder.group({
      (......)
      company_id: this.id2.length //DISPLAY 0
    });
  }

I try also to check it like this:

 ngAfterViewInit() {
    console.log( this.id2); //Display [1,2,3] 
    console.log(this.id2[2]); //Display undefined
    console.log('this.id2.length);//Display 0
  }

How can I get the last id data of the observable and get it into formBuilder?


Solution

  • Set up your form with default/undefined values within the constructor. Then, within (or after) ngOnInit, set it up so that when id$ emits, the last id is written to the company_id value on the form.

    id$.pipe(
      map(a => a.length ? a[a.length - 1]?.id : undefined),
      filter(id => id !== undefined)
    ).subscribe(
      id => this.form.controls.company_id.setValue(id)
    );