从Angular 6中观察到特定值

时间:2019-01-29 20:34:48

标签: angular rxjs ng-bootstrap

使用Angular 6,我正在使用如下接口进行API调用:

服务:

   getEmployees(): Observable<Employees[]> {
    return this.http.get<Employees[]>(this.getEmployeesAPI);
  } 

内部组件:

    ngOnInit() {
        this.employeeService.getEmployees()
          .subscribe(data => {
            console.log(data);
          });

      }

简单模型界面:

export interface Employees {

  fullName: string;

}

API响应看起来像这样,它是一个对象数组,响应中大约有3900个“用户”对象。

[
{
"fullName": "Robert Jones"
},
{
"fullName": "Ian Cooper"
},
{
"fullName": "Jackie Jones"
},
{
"fullName": "Amber Smith"
}
]

如果我将它们显示在表格或其他元素类型网格中,则可以轻松地在模板中使用它们,例如:

{{ data.fullName }}

不过,我需要做的只是获取值列表,即“名称”。出于观察,所以我可以提前使用它们。提前输入的是NG Bootstrap,我已经在stackoverflow上查看了几篇文章两天了,但还没有找到正确的答案。

在NG Bootstrap文档中,他们谈论从服务中进行搜索,但是这会杀死GUI且没有响应,我的想法是预取数据,将它们(数组中的术语)涂抹成一个数组(以mem表示)在本地数组上使用前面的类型。

组件类:

 employees: Employees[];



  //kicks in when 3 characters characters are typed.
  employeeSearch = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      map(search => search.length < 3 ? []
        : this.employees.filter(v => v.fullName.indexOf(search.toLowerCase()) > -1).slice(0, 10))
    )

我尝试使用map并从rxjs中提取,但结果却很糟糕。

1 个答案:

答案 0 :(得分:1)

因此,基本上,您希望将对象数组转换为简单的字符串数组。

理想情况下,您只能使用map

this.employeeService.getEmployees().pipe(
  map((employees: Employees[]) => employees.map(e => e.fullName)),
).subscribe(...);

或者,如果您想做更多的“ Rx方式”,则可以将阵列拆成单个发射体,然后将它们收集回阵列中。

this.employeeService.getEmployees().pipe(
  mergeAll(), // unpack the array
  pluck('fullName'),
  toArray(),
).subscribe(...);
相关问题