In this part we will create an angular service to make a get request to the backend to get the events data.
Creating Angular Service
Open your angular project using visual studio code. Then create a file name “app.service.ts” inside the src->app folder. Then copy and paste this code inside that file.
import { Http } from '@angular/http'; import { Injectable } from '@angular/core'; @Injectable() export class ApiService { constructor( private http: Http) {} getEvents() { this.http.get('http://localhost:3000/events').subscribe(res => { console.log(res); }); } }
What we did is import the required libraries for our service then create a class called ApiService. We inject the Http in the constructor and use it in getEvents function to make a get request to our backend.
To use our service, we need to register it with angular. We can do that in app.module.ts. Import HttpModule and AppService in app.module.ts. Then add HttpModule in imports list and AppService in providers list.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { AppService } from './app.service'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpModule ], providers: [AppService], bootstrap: [AppComponent] }) export class AppModule { }
Now open the app.component.ts and import AppService on it. Then create a constructor and inject the AppService on it. Then call the AppService.getEvents in ngOnInit() function.
import { Component } from '@angular/core'; import { AppService } from './app.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; constructor( private appService: AppService) {} ngOnInit() { this.appService.getEvents(); } }
To check if everything is working. Open your integrated terminal and execute
ng serve --open
If everything is working properly you should get the same response as below.
Related Articles
- MEAN app with Angular 4 (Part 1) Setting up a development environment
- MEAN app with Angular 4 (Part 3) Displaying the data using Angular Material
- MEAN app with Angular 4 (Part 4) Angular Form and Routing
- MEAN app with Angular 4 (Part 5) Saving data to MongoDb
Source Code