从Angular服务传递数据

时间:2017-11-10 22:10:09

标签: angular typescript ionic-framework ionic2 ionic3

我在构造函数中有一个基本方法来计算一年中的当前月份并将值输出到HTML。但是,我似乎无法让它发挥作用。

我是Angular 2和TypeScript的新手,所以这对我来说可能只是一个愚蠢的错误:)

calendar.service.ts文件:

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>

1 个答案:

答案 0 :(得分:1)

组件,您希望使用该服务并显示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以显示服务中的内容

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

您想要获取数据的服务类

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