调用函数并将值放在 angular 表单组中

call function and have the value placed in angular form group

我有一个问题困惑了好久。它最简单,但我超级卡住。

问题是,我有一个函数:

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

我想在我的 fb 组中传递 listTitle 元素:

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

但是我无法让它工作。用 map 和 subscribe 尝试了各种东西,但我的脑海里显然还没有点击。

我还在控制台中看到第一个 console.log 确实打印了所需的值,但第二个没有。所以订阅出了问题。

非常感谢您的观看!

您需要 return 函数中的可观察对象并在需要响应的地方订阅它。

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

并使用 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
  }
});

请参阅 here 以了解为什么需要这样做。