javascript - ako použiť výsledok http.get() pre dva alebo viac nezávislých komponentov?
Chcel som vedieť, ako môžem použiť pole v dvoch komponentoch Angular bez potreby robiť dve požiadavky http.get.
Moja služba.
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());
}
}
Prvá súčasť Tu robím prvú požiadavku.
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;
});
}
}
Druhá súčasť Tu robím druhú žiadosť.
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;
});
}
}
Mohol by som vytvoriť verejné pole v službe? Alebo by to bolo zlou praxou
Odpoveď č. 1
Lepší prístup by bol využiť „caching“.
1) Na zlepšenie vašej architektúry vytvorte jeden súbor http-wrapper.service.ts, ktorý obalí všetky http metódy a bude tu mať jednu vlastnosť na buď čítanie z cache, alebo vykonanie skutočného http get volania. Neukladajte do cache požiadavky typu post a podobne.
2) Okrem toho vytvorte súbor http-cache.interceptor.ts, kde môžete napísať logiku na vykonanie skutočného HTTP GET volania alebo vrátenie výsledku z cache
Toto sú dva najlepšie prístupy, ktoré nielen vyriešia váš problém, ale aj zlepšia vašu architektúru a zvládnu všetky generické požiadavky
Na zdravie (y)