GreenDome
GreenDome

Reputation: 277

Passing data from Angular service

I have a basic method inside a constructor to calculate the current month of the year and output the value to the HTML . However, I can't seem to get it to work.

I'm new to Angular 2 and TypeScript, so this may just be a silly mistake on my behalf :)

calendar.service.ts file:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class GetMonthsService {
  private GetMonthsRef = this.fbDB.list('xxxx/xxxx/months');
  private GetDaysRef = this.fbDB.list('xxxx/xxxxx/months/Days');
  private currentMonth;

  constructor(private fbDB: AngularFireDatabase) {}

  getMonthsList() {
    return this.GetMonthsRef;
  }

  getDaysList() {
    return this.GetDaysRef;
  }

  getCurrentMonth() {
        let currentMonth;
        let d = new Date();
        return this.currentMonth = d.getMonth();
        }

}

home.html:

<ion-content padding>

    <ion-list-header>
      Current Month Page
    </ion-list-header>

          {{currentMonth}}

</ion-content>

Upvotes: 0

Views: 54

Answers (1)

Prithivi Raj
Prithivi Raj

Reputation: 2736

Component, where you would like to consume the service and display HTML

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {appService} from '../../providers/app.service';
import {GetMonthsService} from '../../providers/calendar.service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public appService : appService, public getMonthsService : GetMonthsService) {
    getMonthsService.getCurrentMonth();
  }

}

HTML to display the content from the service

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>From calendar service {{getMonthsService.currentMonth}}</h2>

</ion-content>

Service class where you want to get the data

import { Injectable } from '@angular/core';

@Injectable()
export class GetMonthsService {

  private currentMonth : any;

  constructor() {}


  getCurrentMonth() {
        let d = new Date();
        this.currentMonth = d.getMonth();
        return this.currentMonth;
        }

}

You can refer here for working version

Upvotes: 1

Related Questions