I wanted to know how I do to use an array in two angular components without the need to make two http.get requests.
My service.
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { environment } from '../../../environments/environment';
@Injectable()
export class CategoryService {
constructor(
private http: Http
) {
}
getAll(): Promise<any> {
return this.http.get(`${environment.apiUrl}/categories`)
.toPromise()
.then(response => response.json());
}
}
First component Here I am making the first requisition.
import { Component, OnInit } from '@angular/core';
import { PostService } from './../core/service/post.service';
import { CategoryService } from './../core/service/category.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
categories = [];
constructor(
private postService: PostService,
private categoryService: CategoryService
) { }
ngOnInit() {
this.getAllCategories();
}
getAllCategories() {
return this.categoryService.getAll()
.then(categories => {
this.categories = categories;
})
.catch(error => {
throw error;
});
}
}
Second component Here I am making the second requisition.
import { Component, OnInit } from '@angular/core';
import { CategoryService } from './../core/service/category.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
categories = [];
constructor(
private categoryService: CategoryService
) { }
ngOnInit() {
this.getAllCategories();
}
getAllCategories() {
return this.categoryService.getAll()
.then(categories => {
this.categories = categories;
})
.catch(error => {
throw error;
});
}
}
Could I create a public array in service? or it would be bad practice