Juggernaut
Juggernaut

Reputation: 806

How do I call a function from Service to Component in Angular?

I am trying to learn Angular and I have built an alarm clock. I am giving users a checkbox to select the alarms they want to cancel, I take it in heroes and later use in this.ui(); to store in my lOcal storage.

But my view does not change after the element is deleted. How do I do that?

1) I want to call my function ui(); in the component after my service has finished publishing the alarm.

2) How do I call a function recursively?

Here is my 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);
  }
}

Here is my Alarm Services.

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

Upvotes: 1

Views: 9695

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29775

Even though its not a better approach to call a method in component from service, but still there is a way to do that using 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;              
       }
     }
  }

In your component

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

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

Upvotes: 3

Related Questions