reciosonny
1/28/2018 - 4:34 AM

Injecting global events

Injecting global events

import { GlobalVariable, GlobalVariableStore } from './../global';
import { Injectable, EventEmitter } from '@angular/core';
import { Todo } from '../models/Todo';
import { Http, Headers } from '@angular/http';
import { LoggerService } from './logger.service';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class TodoService {
  private url: string = "api/todo/";
  private cachedTodo: Todo[];
  public itemAdded$: EventEmitter<Todo>;
  public itemDeleted$: EventEmitter<number>;
  public itemUpdated$: EventEmitter<Todo>;
  
  constructor(private http: Http, private loggerService: LoggerService) { 
    this.itemAdded$ = new EventEmitter();
    this.itemDeleted$ = new EventEmitter();
    this.itemUpdated$ = new EventEmitter();
  }

  delete(id: number) {
    const urlDelete = `${this.url}${id}`;
    return this.http.delete(urlDelete, {headers: GlobalVariable.HEADERS_JSON})
      .toPromise()
      .then(() => this.itemDeleted$.emit(id))
      .catch(this.loggerService.handleError);
  }

  save(taskName: string, taskOrder: number): Promise<Todo> {

    return this.http
      .post(this.url, JSON.stringify({ name: taskName, taskOrder: taskOrder, done:false }), {headers: GlobalVariable.HEADERS_JSON})
      .toPromise()
      .then(res => {
        let retVal = res.json().data as Todo;

        this.itemAdded$.emit(retVal);
        return retVal;
      })
      .catch(this.loggerService.handleError);
  }

  update(model: Todo): Promise<Todo> {
    const url = `${this.url}${model.id}`;

    return this.http
      .put(url, JSON.stringify(model), {headers: GlobalVariable.HEADERS_JSON})
      .toPromise()
      .then(() => {
        this.itemUpdated$.emit(model);
        return model;
      })
      .catch(this.loggerService.handleError);
  }

  getTodo(id: number): Promise<Todo> {
    const finalUrl = `${this.url}${id}`;

    return this.http.get(finalUrl)
    .toPromise()
    .then(response => {

      let returnResult: Todo = response.json().data as Todo;
      return returnResult;
    }).catch(this.loggerService.handleError);
  }

  getAll(): Promise<Todo[]> {

    if(GlobalVariableStore.TodoLists.length > 0) { //use GlobalVariableStore to call the REST API once and improve performance.
      // console.log('using globalvariablestore for reusing todo lists');
      // console.log(GlobalVariableStore.TodoLists);
      return Promise.resolve(GlobalVariableStore.TodoLists as Todo[]);
    }

    return this.http.get(this.url)
    .toPromise()
    .then(response => {

      let returnResult: Todo[] = (response.json().data as Todo[])
                                    .sort((x,y) => x.taskOrder - y.taskOrder)
                                    .filter(x => !x.done);
      return returnResult;
    }).catch(this.loggerService.handleError);
  }

}
import { EventHandlerService } from './../../services/event-handler.service';
import { GlobalVariableStore } from './../../global';
import { Component, OnInit, Input, HostListener, EventEmitter, Directive, ElementRef, Inject } from '@angular/core';
import { TodoService } from '../../services/todo.service';
import { Todo } from '../../models/Todo';
import {
  trigger,
  state,
  style,
  animate,
  transition
} from '@angular/animations';

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

  closeResult: string;
  @Input() chkNewTaskTop: boolean;
  tmplModal: any;
  txtTodo: string;

  addTask: boolean = false;
  showFieldBtn: boolean = true;
  todoLists: Todo[] = [];
  private isModalOpen: boolean = false;
  private itemAddedSubscription: EventEmitter<Todo>;
  private itemDeletedSubscription: EventEmitter<number>;
  private itemUpdatedSubscription: EventEmitter<Todo>;
  private initializingSubscription: EventEmitter<void>;
  private itemDoneSubscription: EventEmitter<Todo>;
  
 
  constructor(private todoService: TodoService, private eventHandlerService: EventHandlerService, private toasty: ToastyService, private toastyConfig: ToastyConfig) {
    this.toastyConfig.theme = 'bootstrap';
    this.itemDoneSubscription = new EventEmitter();
    this.itemAddedSubscription = this.todoService.itemAdded$.subscribe(x => this.itemAdded(x));
    this.itemDeletedSubscription = this.todoService.itemDeleted$.subscribe(x => this.itemDeleted(x));
    this.itemUpdatedSubscription = this.todoService.itemUpdated$.subscribe(x => this.itemUpdated(x));
    this.initializingSubscription = this.eventHandlerService.Initialize$.subscribe(x => this.appInitialized());
    this.itemDoneSubscription.subscribe(x => this.doneTodo(x));
  }

  //invoked from app.component.ts. Put all codes to initialize here...
  appInitialized(): any {
  }

  ngOnDestroy() {
    console.log('begin unsubscribing...');
    this.itemAddedSubscription.unsubscribe(); //subscribe to event once...
    this.itemDeletedSubscription.unsubscribe();
    this.itemUpdatedSubscription.unsubscribe();
    this.initializingSubscription.unsubscribe();
  }

//#region emit events
  itemDeleted(id: number) {
    let deletedTodo: Todo = this.todoLists.find(x => x.id === id);
    let deletedTodoIndex: number = this.todoLists.indexOf(deletedTodo);
    this.todoLists.splice(deletedTodoIndex, 1);
    GlobalVariableStore.TodoLists.splice(deletedTodoIndex, 1);
  }

  itemUpdated(model: Todo) {
    // console.log('item updated..')
    let updatedTodo: Todo = this.todoLists.find(x => x.id === model.id);
    // console.log(updatedTodo);
    updatedTodo = model;
  }

  //fire this method when user pressed and confirmed the change in current todo.
  editTodo(model: Todo) {
    console.log(model);
    model.editTodo = false;
    this.todoService.update(model);
  }
  
  itemAdded(item: Todo): void {
    this.determineTodoOrder(item);    
  }
//#endregion
  
}