MEAN app with Angular 4 (Part 2) Getting the data using Angular

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';

export class ApiService {
    constructor( private http: Http) {}

    getEvents() {
        this.http.get('http://localhost:3000/events').subscribe(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';

  declarations: [
  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';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'app';

  constructor( private appService: AppService) {}

  ngOnInit() {

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.

getEvents data

Related Articles

Source Code

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s