1.

Which decorator creates services in Angular 2?

Answer»

The injectable DECORATOR in Angular 2 allows the functionality of the creation of a SERVICE to be injected and used in AngularJS modules by defining it as a PROVIDER in the Component Decorator.

Following is a SYNTAX to successfully create a service using the Injectable() decorator

Example

import { Injectable } from '@angular/core';
import { ITEM } from './item';
import { ITEMS } from './mock-items';
@Injectable()
export class ItemService {
   selectedItems: Item[] = [];
   getItems(): Item[] {
   return ITEMS;
}
getSelectedItems(): Item[] {
   return this.selectedItems;
}
addItem(id:number): void {
   let item = ITEMS.find(ob => ob.id === id);
   if (this.selectedItems.indexOf(item) < 0) {
      this.selectedItems.push(item);
   }
}
removeItem(id:number): void {
   let item = this.selectedItems.find(ob => ob.id === id);
   let itemIndex = this.selectedItems.indexOf(item);
   this.selectedItems.splice(itemIndex, 1);
}



Discussion

No Comment Found