Reputation: 23
I am trying to filter observable objects by the id, but getting error. I have already get some dummy data from json file but have no clue how to display that object into a solid form. Any help?
Service.ts:
export class ProjectService {
private pathurl : string = "/assets/project-data.json";
constructor (private http: HttpClient){}
getProjects(): Observable<ProjectInt[]>{return this.http.get<ProjectInt[]>(this.pathurl)};
Component.ts file:
filterProj(){
var filteredProj = this.projectService.getProjects()
.pipe
(map(projects => this.projects.filter(project => project.id < 3))
);
return filteredProj;
}
Components.html:
<a class="button" (click)="filterProj()"><span>DESIGN</span></a>
Upvotes: 1
Views: 169
Reputation: 54
You need to return the filtered list from the map
operator.
filterProj() {
this.projectService.getProjects().pipe(
map(projects => {
const filteredList = projects.filter(project => project.id < 3);
return filteredList;
})
);
}
Or you could use the filter
operator.
filterProj() {
this.projectService.getProjects().pipe(
filter(project => project.id < 3)
);
}
Update: I missed the subscription part. As @Nicholas K suggested in his answer, you need to subscribe to your observable to get the value of it.
One suggestion: filter
operator is more readable than map
operator when you need to filter data.
Upvotes: -1
Reputation: 15423
Couple of issues:
You need to subscribe to the observable to actually get data from it:
data;
filterProj(){
this.projectService.getProjects()
.pipe
(map(projects => this.projects.filter(project => project.id < 3))
)
.subscribe(response => this.data = response);
}
Store the response from the observable in a variable, for eg:
data
. Now you can use this in your template:
<div *ngIf="data">
{{ data | json}}
</div>
Upvotes: 2