【问题标题】:Observable object array doesn't work in a pipe可观察对象数组在管道中不起作用
【发布时间】:2020-06-29 15:25:56
【问题描述】:

我正在尝试创建一种从服务中搜索用户信息的自动完成方法。 首先,我创建了一个方法,该方法回调服务并返回 UtilisateurCreationDto[] 的 Observable:

   autoCompleteDuplication(duplicated_name :string): Observable<UtilisateurCreationDto[]>{
        console.log("in in");

        return this.userCreationService.autoCompleteDuplication(duplicated_name);
    }

*模型 UtilisateurCreationDto 是具有属性的简单类。 该方法被称为如下:

search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 2 ? []
        : this.autoCompleteDuplication(term).subscribe(data=>{

        data.filter(v => v.nom.toLowerCase().startsWith(term.toLocaleLowerCase()))
        })
        )
    );

在 html 模板上,我在 [ngbTypeahead] 上调用搜索:

      <input id="typeahead-config" type="text" [(ngModel)]="duplication_name" 
        [ngbTypeahead]="search"
        />

当我尝试在搜索字段中输入文本时出现此错误:

Uncaught Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

您知道为什么返回类型 UtilisateurCreationDto[] 不适用于我的实现吗?如果我用静态字符串 [] 更改服务调用,知道这很好。

问候

【问题讨论】:

    标签: angular rxjs observable angular2-observables angular-pipe


    【解决方案1】:

    在这种情况下,您应该使用SwitchMap 而不是Map pipe

    search = (text$: Observable<string>) =>
        text$.pipe(
          debounceTime(200),
          distinctUntilChanged(),
          switchMap(term => term.length < 2 ? of([])
            : this.autoCompleteDuplication(term).pipe(map(data=>{
    
             return data.filter(v => v.nom.toLowerCase().startsWith(term.toLocaleLowerCase()))
            }))
            )
        );
    

    【讨论】:

      【解决方案2】:

      我建议您重构您的搜索方法,如下所示,并改用 switchMap

      search = (text$: Observable<string>) =>
      text$.pipe(
        filter((trm) => trm.trim().length > 2),
        debounceTime(200),
        distinctUntilChanged(),
        switchMap(term => this.autoCompleteDuplication(term).pipe(
          map((data)=> data.filter(v => v.nom.toLowerCase().startsWith(term.toLocaleLowerCase()))
         ))
      );
      

      【讨论】:

        猜你喜欢
        • 2020-07-18
        • 1970-01-01
        • 2012-06-13
        • 1970-01-01
        • 2019-10-31
        • 2019-09-09
        • 1970-01-01
        • 2021-08-07
        • 2012-04-20
        相关资源
        最近更新 更多