Find an Object of an Http Array with an Angular pipe2

1

I want to make an http request to a Json and this returns an array of comments, from that Array I want to directly get the comments that have an Id that matches the one that happened, all directly:

export class DetailUserComponent implements OnInit {

  comments: Comments[];


  constructor(
    private conexionComment: ConexionCommentsService) { }

   ngOnInit() {
         this.conexionComment.getCommentsPerson(0)
              .subscribe(comments => this.comments = comments);
  }
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { Comments } from './Class/comments';

@Injectable()
export class ConexionCommentsService {
  comments: Comments[];

  constructor( private http: HttpClient) { }

  getCommentsPerson(id: number): Observable<Comments[]> {
    const url = 'assets/Json/listComment.json';
    return this.http.get<Comments[]>(url).pipe(find(myComment => this.comments.idUser === id));
  }

The idea is to find the object in the Array of objects, the object.idUser === to the id that passed '0' The problem is that when I put this.comments.YA I do not have access to the attributes of the object

    
asked by EduBw 12.04.2018 в 09:10
source

1 answer

1

The simplest way to filter an array is by using its filter method:

let users=[];

for (let i=5;i<40;i+=5) {
  users.push({idUser:i, name: 'user'+i});
}

//Tenemos estos usuarios
users.forEach(u=> console.log(u.name,u.idUser));

let filtered=users.filter(u => u.idUser>10 && u.idUser<30);
console.log('Después de filtrar')
filtered.forEach(u=> console.log(u.name,u.idUser));
  

If you apply find to the observable or to its Stream (which is what you get in the function pipe() ), it will filter that observable, not its content: That is, if the observable one returns an array, filter can let it pass or not , but not part of it.

Adding all this:

getCommentsPerson(id: number): Observable<Comments[]> {
  const url = 'assets/Json/listComment.json';
  const result=this.http.get<Comments[]>(url);
  return result.map((comments: Comments[]) => {
    return comments.filter(myComment => myComment.idUser === id);
  }
}
    
answered by 12.04.2018 / 10:20
source