Consider the utterly simple Angular 2 service:
import { Injectable } from \'@angular/core\';
import {Category} from \"../models/Category.model\";
@Injectabl
Not too big of a boilerplate chunk. But what's going on here is that when the service is created or you make a call however your want to handle it. Your component will know about it through the subscription and then update your local variable to the new value. Allowing you to access it as this.activeCategory.
import { Injectable } from '@angular/core';
import {Category} from "../models/Category.model";
import {Subscription} from 'rxjs/Subscription';
@Injectable()
export class CategoryService {
private _categoryObject = new Subject();
categoryObjectAnnounced$ = this._categoryObject;
private _activeCategoryObject = new Subject();
activeCategoryObjectAnnounced$ = this._activeCategoryObject;
activeCategory: Category|{} = {};
constructor() {};
}
import { Component, OnInit } from '@angular/core';
import {CategoryService} from "../shared/services/category.service";
import {Category} from "../shared/models/Category.model";
import {Subscription} from 'rxjs/Subscription';
@Component({
selector: 'my-selector',
template: `
{{activeCategory.Name}}
{{category.Name}}
`,
})
export class MySelectorComponent implements OnInit {
category:Category|{} = {};
activeCategory:ActiveCategory|{} = {};
activeCategorySubscription : Subscription;
categorySubscription : Subscription;
constructor(public categoryService:CategoryService){
this.categorySubscription= this.categoryService.categoryObjectAnnounced$.subscribe((category) => {
this.category= category;
});
this.activeCategorySubscription= this.categoryService.activeCategoryObjectAnnounced$.subscribe((active) => {
this.activeCategory= active;
});
};
ngOnInit() {
};
}