In the previous post we have the angular app created with a simple service, but the data from that service is stored in a JSON variable.
Could we get this data from a MongoDB database? Of course, yes! But, indeed, we don´t access to a MongoDB db, but also through and API REST in the server side… and in the server is the component that access to the Mongo DB. Ok, but what are the steps to do that…?
Let´s see it on this post
The Full Source Code is available on GitHub:
Our project, how we left from the previous post, look like this:
and the result when we run the app is the following:
#01: API REST — The server Side
Let´s add the data, we can use postman:
or we can use robomongo instead:
#02: Front End — The client Side
The steps in angular2 to consume an API REST is by using an HTTP component, that we should define as provider. If we created our project with angular-cli we already have this component defined as a provider
So, let add it to service:
Our service class have the hard components:
Next, let´s add the service, using the http module an the promises
#03: Front End — Backend Integration
So, we should enable CORS origin with the following config on server:
and the result is the page with data from the Mongo Db through the API REST
thats the reason on Nodejs+express compponent app_users.js add the following line of code:
We can observe that invocation is async, because we use a Promise. But there is a second o less that data in the front have undefinited values until the data with the promise arrive. This delay produce an error in the home page that crashed the app:
the other possibility is avoid undefined values setting an empty array when the class is created.
Closing the post:
Let´s end the post at this point. we should also implement the other methods (save User, update User, etc), also we could explore other two ways to consume the api rest:
a) without promises, and with “map”: It is very common
and a subscribe
But let´s stop the post at this point because we get the idea…
We can establish a connection between the front, backend and the API REST
So, we have a front in Angular, an API Rest in Express and Node.js and a Database with MongoDB
If you want to get the source Code, it is available on GitHub:
See you in another post, while we are sharing while we are learning .