Using the User Id on the Frontend in MEAN Stack
In our previous section, we successfully passed the user id to the front end. We are handling the user-id now, and in this section, we will use the user id in the post-list component with the creator. We will use the following steps to use it on the frontend:
1) We have already set the userId property in the typescript file of the post-list component. We will use it in conjunction with the creator information which we have on every post. In the post-list component, every post that we render onto the screen will have the creator Id. We will go to the html file, and there we will add another condition to the ngIf statement. We want to show the edit and delete buttons when the user is authenticated, and the userId is equal to the creator of the post.
2) We get an error in the template because of our post model. In the post model, there doesn't have that creator field. So, we will add the creator field in our post model, and this field will also be of type string.
3) After adding this, we will get an error in the post.service.ts file where we update a post. We get this error because we are not sending that creator id. We will simply set the creator to null.
4) We could definitely take the Id of the user who is currently logged in, but that would open the window for the user to manipulate that, and we don't want that. So instead, we need to handle this on the server. We will go back to our posts.js routes where we update a post, we need to add the creator field again, but this time we take that data from the user data we have in the request.
5) We will also get an error in the typescript file of the post-create component. There we have a post which we are trying to load when we are editing a post. There we are missing the creator field, so we will add this like as:
6) This will give an error because we are not adding that creator filed in our post-service where we are getting that single post. So, we will add it in the getPost() method of our post service:
Everything is looking good. Now we will go back to our angular app and check whether our app is working properly or not.
Our application is working well, and this is exactly what we want. From the next section, we will start a new module, i.e., Handling Errors.
Download Complete Project(Authorization.zip)