I am doing a webproject where i need friendship/follow functionality. I also have two roles admins and (regular) users. Users can follow other users. Admins can not follow users.
A user can follow another user by clicking on a Follow ("Volgen)" button. If the user already follows an user an unfollow ("ontvolgen") will be shown. With the use of a custom pure pipe i check wether the user already follows a user.
A users sees either the follow or unfollow button. An admin is only able to see a delete button.
This is the code of the pipe:
@Pipe({
name: 'includes',
pure: true,
})
export class IncludesPipe<T> implements PipeTransform {
transform(array: T[], item: T): boolean {
return array.includes(item);
}
}
This is the use of the custom created 'includes' pipe in html:
<div
<table >
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Voornaam</th>
<th scope="col">Achternaam</th>
<th scope="col">Stad</th>
<th *ngIf="isUser || isAdmin" scope="col"></th>
</tr>
</thead>
<tbody *ngIf="users.length > 0">
<tr *ngFor="let user of filteredUsers; let i = index">
<th scope="row">{{ i 1 }}</th>
<td>{{ user.firstName | titlecase }}</td>
<td>{{ user.lastName | titlecase }}</td>
<td>{{ user.city | titlecase }}</td>
<div
*ngIf="
currentlyFollowing | includes : user._id;
then unfollowTemplate;
else followTemplate
"
></div>
<ng-template #followTemplate>
<td>
<a
(click)="followUser(user._id)"
>Volgen</a
>
</td>
</ng-template>
<ng-template #unfollowTemplate>
<td>
<a
(click)="unfollowUser(user._id)"
>Ontvolgen</a
>
</td>
</ng-template>
<td *ngIf="isAdmin">
<a
(click)="sweetAlertDeleteConfirmation(user._id)"
>
Verwijderen
</a>
</td>
</tr>
</tbody>
<tbody *ngIf="users.length === 0">
<td colspan="5">
<h2 >Er zijn geen leden gevonden!</h2>
</td>
</tbody>
</table>
I keep track of the role of the current logged in user with a boolean: "isUser". This works perfectly untill i add another expression in ngIf statement where the pipe is located like so:
<div
*ngIf="
isUser && currentlyFollowing | includes : user._id;
then unfollowTemplate;
else followTemplate
"
></div>
When im logged in with an admin account and thus isUser equals false, the data is not loaded correctly. first images shows correct data:
(note: reload build-in browser on sandbox manually, it acts a bit buggy)
CodePudding user response:
I assume statement isUser && currentlyFollowing
is computed first, which results in boolean. Then this boolean value gets passed into your includes
pipe, hence your array.includes is not a function
error.
I'd suggest you to start debugging by checking what type (value) you get inside the pipe.
If that's the case, use parentheses to override operator precedence like: isUser && (currentlyFollowing | includes : user._id)
.