I'm trying to make something that looks like this:
Looking for a way to make Service feed the latest data to subscribed components whenever its necessary. For example: Component3 writes changes to the API > Component1 and Component2 have to get the latest data.
Currently both components are subscribed to an observable returned by the service and this causes 2 API requests if both are rendered. This feels wrong. In my understanding these components should be fed the data and not request it on their own. To be clear: the data returned by this service is always being used in Component1 while Component2 is rendered optionally.
Here's some snippets and a bit of description of what I've done so far:
Service gets data through HTTP from API. Component1 and Component2 are subscribed to observable returned by Service:
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
@Injectable()
export class GroupService{
constructor(private _http: Http){}
getGroups(){
return this._http.get('/assets/groups.json')
.map((res) => {
return res.json();
});
}
}
Component1 and Component2 are basically the same in terms of functionality. Here's one of them:
import { Component } from '@angular/core';
import { router } from '../../app.router';
import { GroupService } from '../../services/group.service';
import { Group } from '../../interfaces/group.interface';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss'],
})
export class SidebarComponent
{
router;
groups: Group[];
constructor(private _groupService: GroupService){
this.router = router;
this.getGroups();
}
getGroups(){
this._groupService.getGroups()
.subscribe((groups) => {
this.groups = groups;
});
}
}