Javatpoint Logo
Javatpoint Logo

Connecting Angular to the API Endpoint in MEAN Stack

In our previous section, we set up the post backend point with the help of the app.post() method, but we didn't connect angular to it. So, in this section, we will connect angular to the API endpoint. We will add some line of code, and we also need to replace some code for this, which are as follows:

1) In our post middleware, we didn't use the next() function. So, the post request will not reach to the last middleware. For this, we will call the get method instead of use() in the last middleware.


Connecting Angular to the API Endpoint in MEAN Stack

2) We will go back to our post-create.component.ts file. In this file, we have triggered the addPost() method, so we need to send our request in this method.

We will go back to this method in the posts.service.ts file. We will send our request before pushing the post. We will use http.post() method here and pass the url which will be the same as for the get request but with a different http verb like:

The post request also get back some data, so we need to define it with generic type. We know we will just get a message from it, which is of type string.

We also need to pass the second argument here, and that is the data which we want to post like this:


Connecting Angular to the API Endpoint in MEAN Stack

3) As before, nothing will happen if we don't subscribe. So, we will call the subscribe method like this:

The subscribe method has typical handler also. We will handle the success case and get back my response data in the following way:


Connecting Angular to the API Endpoint in MEAN Stack

4) We use optimistic updating by adding the following lines of code at the end:

But, we need to switch from optimistic updating to only updating. We will do this by adding these two calls in the subscribe method because this will execute asynchronously only one we got a success response.


Connecting Angular to the API Endpoint in MEAN Stack

5) Now, we will restart the ng server and node server again. When we add a new post in our angular app, we will get a success message and a post object in our server-side log like this:

Connecting Angular to the API Endpoint in MEAN Stack
Connecting Angular to the API Endpoint in MEAN Stack

Download Complete Project(Connecting angular to the API endpoint.zip)


Next TopicWhat is MongoDB




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA