In our previous demo, we have already learn about the basic app creation and routing in angular2. So now we are going to create a demo which will fetch data from server using http calls.
Since we all know that data over content of dynamic sites are stored somewhere in the database. So http calls are used in angular application or any other frontend technology to fetch data from server. So http calls plays a very important role any application.
Here we will continue ahead of the task which we have already discussed in the previous demo. So ahead in this demo we will discuss mainly over http calls part within the app. So we will create a basic app which will show the list of some user on the very first page.
To use the Angular 2 Http module in our components, Http module is import with in the app.
After that, we can just inject it via Dependency Injection in the constructor.
So now I am going the create a service file within app/ folder named user.service.ts.
Angular 2 introduces new annotation to declare the class as Injectable. You can read in depth from the official site.
In the above file we have imported needed class of angular and then defined a function fetchcUsers(). In which we are calling a restful api to get the user list from the server.Another thing is that we are not using callbacks or promises in the HTTP calls. Instead what we are using is called Observables.
You can learn more about the Observables from the officail sites.
so lets move to next file inside component home/home.component.ts
In the above file, At top call the user service and inside class on ngOnInit() call the fetchUsers() method. Similarly we can call multiple service method.
For node server end task, start node server using node server.js from from the root folder.
Angular2 HTTP calls with observables is really amazing feature in angular2. We can perform the same task with converting the observables to promise.
You can download complete code from here. Download Code