如何获取Observable Array属性的唯一值 - Angular

时间:2018-05-07 14:31:51

标签: javascript html angular

我有一个Angular应用程序,它有一个从伪API获取数据的服务,它返回一个对象数组,如下所示:

[
  {
    "userId": 1,
    "id": 1,
    "title": "quidem molestiae enim"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "sunt qui excepturi placeat culpa"
  },
  {
    "userId": 2,
    "id": 3,
    "title": "omnis laborum odio"
  },
  {
    "userId": 2,
    "id": 4,
    "title": "non esse culpa molestiae omnis sed optio"
  },
  {
    "userId": 3,
    "id": 5,
    "title": "eaque aut omnis a"
  },
  {
    "userId": 4,
    "id": 6,
    "title": "natus impedit quibusdam illo est"
  },
  ]

我想要的是获得 userId 属性的唯一值而不重复,所以我应该得到以下值: 1 2 3 4

那么如何在Angular4中实现它。

这是我的代码:

1- Service.ts:返回所有数据而不过滤重复值。

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import 'rxjs/add/operator/map'
import "rxjs/Rx";



@Injectable()
export class AlbumsService {


  constructor(private _http:HttpClient) { }
  serveLink:string = "https://jsonplaceholder.typicode.com/albums"

  getUniqueUserIDs():Observable<IAlbums[]>
  {
    return this._http.get<IAlbums[]>(this.serveLink).map(response=>response)
  }

}

2-FilterComponent.ts:在这里,我通过订阅observable在控制台中记录结果。

import { Component, OnInit } from '@angular/core';
import { AlbumsService } from '../albums.service';


@Component({
  selector: 'app-filter-albums-by-user-id',
  templateUrl: './filter-albums-by-user-id.component.html',
  styleUrls: ['./filter-albums-by-user-id.component.css']
})
export class FilterAlbumsByUserIdComponent implements OnInit {

  constructor(private _albumsService:AlbumsService) { }

  ngOnInit() 
  {

    this._albumsService.getUserIDs()
    .subscribe 
     ((response)=>
      {
        console.log(response)
      }
    )

  }
}

其他重要问题,在这种情况下,我应该在哪里写逻辑? 在Service方法中还是在Component的订阅中?

谢谢。

2 个答案:

答案 0 :(得分:1)

通过ES6使用新的设置,

&#13;
&#13;
const response = [
  {
    "userId": 1,
    "id": 1,
    "title": "quidem molestiae enim"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "sunt qui excepturi placeat culpa"
  },
  {
    "userId": 2,
    "id": 3,
    "title": "omnis laborum odio"
  },
  {
    "userId": 2,
    "id": 4,
    "title": "non esse culpa molestiae omnis sed optio"
  },
  {
    "userId": 3,
    "id": 5,
    "title": "eaque aut omnis a"
  },
  {
    "userId": 4,
    "id": 6,
    "title": "natus impedit quibusdam illo est"
  },
  ];

const uniqueIds = [...new Set( response.map(obj => obj.userId)) ];
console.log(uniqueIds);
&#13;
&#13;
&#13;

您应该在组件级别执行此操作。

答案 1 :(得分:1)

使用mapdistincttoArray

return this._http.get<IAlbums[]>(this.serveLink).map(t=>t.userId).distinct().toArray();