|
1 | 1 | import { Injectable } from '@angular/core';
|
| 2 | +import { Http, Response } from '@angular/http'; |
| 3 | +import { Observable } from 'rxjs/Observable'; |
| 4 | +import 'rxjs/add/observable/throw'; |
| 5 | +import 'rxjs/add/operator/catch'; |
| 6 | +import 'rxjs/add/operator/do'; |
| 7 | +import 'rxjs/add/operator/map'; |
2 | 8 |
|
3 | 9 | import { IProduct } from './product';
|
4 | 10 |
|
5 | 11 | @Injectable()
|
6 | 12 | export class ProductService {
|
| 13 | + private _productUrl = 'api/products/products.json'; |
7 | 14 |
|
8 |
| - getProducts(): IProduct[] { |
9 |
| - return [ |
10 |
| - { |
11 |
| - "productId": 2, |
12 |
| - "productName": "Garden Cart", |
13 |
| - "productCode": "GDN-0023", |
14 |
| - "releaseDate": "March 18, 2016", |
15 |
| - "description": "15 gallon capacity rolling garden cart", |
16 |
| - "price": 32.99, |
17 |
| - "starRating": 4.2, |
18 |
| - "imageUrl": "http://openclipart.org/image/300px/svg_to_png/58471/garden_cart.png" |
19 |
| - }, |
20 |
| - { |
21 |
| - "productId": 5, |
22 |
| - "productName": "Hammer", |
23 |
| - "productCode": "TBX-0048", |
24 |
| - "releaseDate": "May 21, 2016", |
25 |
| - "description": "Curved claw steel hammer", |
26 |
| - "price": 8.9, |
27 |
| - "starRating": 4.8, |
28 |
| - "imageUrl": "http://openclipart.org/image/300px/svg_to_png/73/rejon_Hammer.png" |
29 |
| - }, |
30 |
| - { |
31 |
| - "productId": 10, |
32 |
| - "productName": "Video Game Controller", |
33 |
| - "productCode": "GMG-0042", |
34 |
| - "releaseDate": "October 15, 2015", |
35 |
| - "description": "Standard two-button video game controller", |
36 |
| - "price": 35.95, |
37 |
| - "starRating": 4.6, |
38 |
| - "imageUrl": "http://openclipart.org/image/300px/svg_to_png/120337/xbox-controller_01.png" |
39 |
| - } |
40 |
| - ]; |
| 15 | + constructor(private _http: Http) {} |
| 16 | + |
| 17 | + getProducts(): Observable<IProduct[]> { |
| 18 | + return this._http.get(this._productUrl) |
| 19 | + .map((response: Response) => <IProduct[]> response.json()) |
| 20 | + .do(data => console.log('All: ' + JSON.stringify(data))) |
| 21 | + .catch(this.handleError); |
| 22 | + } |
| 23 | + |
| 24 | + private handleError(error: Response) { |
| 25 | + console.error(error); |
| 26 | + return Observable.throw(error.json().error || 'Server error'); |
41 | 27 | }
|
42 | 28 | }
|
0 commit comments