如何在Angular中调用Service到Component的函数?

时间:2017-05-04 23:48:36

标签: angular

我正在努力学习Angular,我已经建立了一个闹钟。我给用户一个复选框来选择他们要取消的闹钟,我把它带到英雄中,然后在this.ui()中使用;存放在我的lOcal存储器中。

但删除元素后我的视图不会改变。我该怎么做?

1)我想调用我的函数ui();我的服务发布完警报后,在组件中。

2)如何递归调用函数?

这是我的register.component.ts

import { Component, OnInit } from '@angular/core';
import {ValidateService} from '../../services/validate.service';
import {AlarmService} from '../../services/alarm.service';
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '@angular/router';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

   hours;
   id: String;
   timeid: String;
   time;
   heroes: any[];
   name:string;
   hero = [1,2,3,4,5].map(id => <any>{id:id, time: new Date(2017,5,id)})


  constructor(
    private validateService: ValidateService, 
    private FlashMessage: FlashMessagesService,
    private Router: Router,
    private AlarmService: AlarmService
    ) { 

      }

  ngOnInit() {

     this.ui();
  }


  ui(){
    setTimeout(() => {
     this.heroes = JSON.parse(localStorage.getItem('users'));
     console.log(this.heroes);
       }, 100);  
  }

  check(e){
    console.log(e);
    console.log(e.target.checked);
    console.log(e.target.value);

     let get = JSON.parse(localStorage.getItem('users'));
     for(var i= get.length -1 ; i > -1; i--) {
          if(get[i].id == e.target.value) {
              get.splice(i, 1);
          }
      }
     localStorage.setItem('users', JSON.stringify(get)); 

     console.log(get); 

     this.ui();

     let time = new Date().getTime()

     this.AlarmService.setUpAlarms(time);
  }
}

这是我的闹钟服务。

import { Injectable } from '@angular/core';
import {FlashMessagesService} from 'angular2-flash-messages';


@Injectable()
export class AlarmService {
   constructor(private FlashMessage: FlashMessagesService) {}

   setUpAlarms(time: number){


    var storage =  JSON.parse(localStorage.getItem('users'));
    var alarms = [];
    var miliseconds = [];
    var eventNow = new Date();
      for(var i=0; i < storage.length; i++){
        var eventEndTime = storage[i]['hours'];
      var flag = storage[i]['flag'];
        if (eventEndTime >= new Date()) {
          alarms.push(storage[i]);
          var duration = eventEndTime.valueOf() - eventNow.valueOf();
          miliseconds.push(duration);
          miliseconds = miliseconds.sort((a, b) => a - b);
      }
      }
      console.log(miliseconds);
      localStorage.setItem('users', JSON.stringify(alarms));

       for(var i =0; i< miliseconds.length; i++){
          setTimeout(() => {
            this.FlashMessage.show('ALARM CLOCK WAKE UP', {cssClass: 'alert-danger', timeout: 10000});

            }, miliseconds[i]);    

            return;              
       }
     }
  }

1 个答案:

答案 0 :(得分:0)

尽管从服务中调用组件中的方法不是更好的方法,但仍有一种方法可以使用Subject来实现。

import { Injectable } from '@angular/core';
import {FlashMessagesService} from 'angular2-flash-messages';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AlarmService {
   constructor(private FlashMessage: FlashMessagesService) {}

  // Observable string sources
  private compInstance= new Subject<any>();
  // Observable string streams
  comp$ = this.compInstance.asObservable();

   setUpAlarms(time: number){
    var storage =  JSON.parse(localStorage.getItem('users'));
    var alarms = [];
    var miliseconds = [];
    var eventNow = new Date();
      for(var i=0; i < storage.length; i++){
        var eventEndTime = storage[i]['hours'];
      var flag = storage[i]['flag'];
        if (eventEndTime >= new Date()) {
          alarms.push(storage[i]);
          var duration = eventEndTime.valueOf() - eventNow.valueOf();
          miliseconds.push(duration);
          miliseconds = miliseconds.sort((a, b) => a - b);
      }
      }
      console.log(miliseconds);
      localStorage.setItem('users', JSON.stringify(alarms));

       for(var i =0; i< miliseconds.length; i++){
          setTimeout(() => {
            this.FlashMessage.show('ALARM CLOCK WAKE UP', {cssClass: 'alert-danger', timeout: 10000});

            }, miliseconds[i]);    

       this.compInstance.next();        // Notify alarm published
            return;              
       }
     }
  }

在您的组件中

this.AlarmService.comp$.subscribe(
        () => {
            this.ui()
        }
);

参考:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service