Brooke Clonts Brooke Clonts - 4 months ago 54
HTTP Question

Angular2 Service running http method only once

I have a service that requests info from the server. I only need to run the request once and make it available to every component. So far I have:

@Injectable()
export class ProductService {
private products: Observable<IProduct[]>;
private _productUrl = 'app/api/products2.json';

constructor(private _http: Http) {
console.log(this.products);
this.products = this.setProducts();
}

setProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]>response.json())
.do(data => console.log('A: ' + JSON.stringify(data)))
.catch(this.handleError);
}

getProducts(): Observable<IProduct[]> {
return this.products;
}

private handleError(error: Response) {
return Observable.throw(error.json().error || 'Server error');
}
}


When the route changes, it runs the constructor
setProducts
line again.
this.products
is always undefined when it's logged so doing an if statement doesn't work. What can I change to make sure this http request isn't running when the service should already have that info?

Thanks!

Answer

do this in your bootstrap

it's because each time a new instance of service is created for each component

import {ProductService } from './app/services/product.service'; //put your path not mine
import { provide } from '@angular/core';
import {ReflectiveInjector} from '@angular/core';

let injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS);
let http = injector.get(Http);
let prodService = new ProductService (http);    

bootstrap(AppComponent, [ 
  [provide(ProductService ,{useValue:prodService})]
]).catch(err => console.error(err));