Im migrating my angularJS app to the new angular (v5.x). I have a basic CRUD application where I pull all my data from a REST service and share it across multiple areas of my app.
I am trying to re-create that app in the new angular framework (v5.x). Where I am struggling to understand is what is the best way to store de data?
In AngularJS I used to store my data into a main scope and then had that consumed by various areas of the app. I would need to do the same for my various components.
Reading multiple guides I got my basic HTTP service working:
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import { Incident_Model } from './incident_model';
const BackEnd_URL = environment.BackEnd_URL;
@Injectable()
export class CommonService {
constructor(private http: HttpClient ) { }
// API: GET /incidents
getAllIncidents(): Observable<Incident_Model[]> {
return this.http.get<Incident_Model[]>(BackEnd_URL + '/Incidents');
}
}
From here, what would be the best practice to follow to share that data across my components without forcebly having to call the API multiple times? Looking into various guides, nothing seems to match my scenario.
This is what I had going using the Angular Material table but this seems to call the API which is what im trying to avoid. I would prefer only calling the API once on Init and then somehow fetching that data locally when I need it.
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { CommonService } from '../common.service';
import {Observable} from 'rxjs/Observable';
import {DataSource} from '@angular/cdk/collections';
import { Incident_Model } from '../incident_model';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
constructor (private commonService: CommonService) {}
public dataSource = new IncidentDataSource(this.commonService);
displayedColumns = ['test1', 'test2', 'test3', 'test4'];
ngOnInit(){}
}
export class IncidentDataSource extends DataSource<any> {
constructor(private commonService: CommonService) {
super();
}
connect(): Observable<Incident_Model[]> {
return this.commonService.getAllIncidents();
}
disconnect() {}
}