Much more manageable than some of our previous service methods!
Add Controller Method
[HttpPost("{id}/read")]publicasyncTask<IActionResult>MarkMessageAsRead(intuserId,intid){if(userId!=int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))returnUnauthorized();varmessage=await_messageService.GetMessage(id);if(message.RecipientId!=userId)returnBadRequest("Failed to mark message as read.");if(await_messageService.MarkMessageAsRead(message))returnNoContent();thrownewException("Error deleting the message");}
Add Service Method in Angular
In user.service.ts - add a new method called markAsRead()
We can make the method here self-subscribing, which means we don't have to subscribe to it in our component and write a separate method - we can just use it in loadMessages() in our member-messages.component.ts.
First, let's import the do operator from rxjs. This will allow us to 'do' something with the messages array before we subscribe to it. In our case, we want to check if the messages are marked as read.
We'll also bring in underscore again.
This is a bit trickier in the JavaScript/TypeScript than what we've done so far. But, think back to how we're manipulating data in some of our service methods on the backend with LINQ and it's very relatable.
Since we need it again, we'll store this in a variable this time to make it reusable.
We're calling our service method as usual - but, changing the first parameter to the variable we just created.
We're calling the rxjsdo operator that let's us 'do' something with the data before we subscribe to it.
This is what we're 'doing': we're using the underscoreeach() function to loop through an array and apply a callback function to each element.
In the callback function, we're checking if the message isn't marked as read and if the user that is loading the messages is the recipient.
If so, we call the markAsRead() function we just wrote.
Test It!
Open up the browser, log in as one user in a message conversation - navigate to the MemberMessage component, view the messages, and then log in as the other user.