Search code examples
angularfunctionsubscription

call function and have the value placed in angular form group


I have an issue which I am puzzled for quite a while. It most be very simple, but I am super stuck.

The issue is, I have a function:

    public getListTitle(): any {
    const listId = this.route.snapshot.paramMap.get('listId');
    console.log("het list-id = " + listId);
    this.listService.getListNo404(listId).subscribe(list=>{
    this.listTitle= list.listTitle ;
    console.log(this.listTitle);
    });
    console.log(this.listTitle);
    return this.listTitle;
  }

And I would like to have the listTitle element passed in my fb group:

{
    
    this.newList = this.fb.group({
      'listTitle': [this.getListTitle()],
      'listId':['873'],
      'listCreator':[this.username],
      'sublist': this.fb.array([
        this.initSublist() 
      ])
    });

However I am just not able to make it work. Tried all kinds of things with map and subscribe, but something clearly does not click in my mind yet.

I also see in the console that the first console.log does print the desired value, however the second doesn't. So something is going wrong in the subscription.

Thanks a lot for having a look!


Solution

  • You need to return the observable from the function and subscribe to it where it's response is required.

    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    public getListTitle(): Observable<any> {
      const listId = this.route.snapshot.paramMap.get('listId');
      return this.listService.getListNo404(listId).pipe(
        map((list) => list.listTitle)   // <-- use `map` operator to return `listTitle`
      );
    }
    

    And use the observable

    this.getListTitle().subscribe({
      next: (listTitle: any) => {
        this.newList = this.fb.group({
          'listTitle': [listTitle],
          'listId':['873'],
          'listCreator':[this.username],
          'sublist': this.fb.array([
            this.initSublist() 
          ])
        });
      },
      error: (error: any) => {
        // handle errors
      }
    });
    

    See here to learn why you'd need to do it this way.