I am trying to create a custom pipe for getting likes on particular post, it has a service which connects to database and pull all likes related to particular post, but when i try to run in my code, i am getting return value before the getting response from service, i know i should wait for the response but not sure how to do that.. please help me resolve this issue.
HTML page
<a [ngClass]="{'like': toggle, 'dislike': !toggle}" (click)="addremovecomment($event, mainpost)" class="float-right btn-sm text-black btn mr-1 dislike"><span><i class="fa fa-heart" style="color: dislike;"></i></span><label class="ml-1" id="lbl{{mainpost.id}}">{{mainpost | like }}</label></a>
Service
getalllikes(post: MainPost): Observable<any> {
return this.http.post<any>(this.baseUrl + 'GetLikes', post);
}
Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { MainPost } from '../_models';
import { LikesService } from '../_services';
import { retry } from 'rxjs/operators';
@Pipe({
name: 'like'
})
export class LikePipe implements PipeTransform {
postlikes = 0;
constructor(private likeservice: LikesService) {
}
transform(post: MainPost, ...args: any[]): any {
const UserId = localStorage.getItem('UserId');
this.getlikes(post);
if (this.postlikes === 0) {
return '0 Likes';
} else {
return this.postlikes + ' Likes';
}
}
getlikes(post: any) {
this.likeservice.getalllikes(post).subscribe(data => {
console.log();
// likes = data;
this.postlikes = data;
}, (err: any) => console.error(err));
}
}
ngOnInit()of your component and within the subscription, set the property that you bind in the template to the result of the http call. Basically move the code from your pipe to your component.