summaryrefslogtreecommitdiff
path: root/recipeBuddy/src/app/REST_service/backend.service.ts
blob: cc08bc621e2872ca45703d06bb9ce7dc827b45a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { retry, catchError, map } from 'rxjs/operators'
import { Recipe } from '../DataModels/recipe'


export interface Status {
	Code: number;
	Msg: string;
}
export interface MsgList {
	Status: Status;
	Data: number[];
}

export interface Msg {
	Status: Status;
	Data: Recipe;
}


@Injectable({ providedIn: 'root' })

/* BackendService class based on tutorial at:
 * <https://www.positronx.io/angular-8-httpclient-http-tutorial-build-consume-restful-api/>
 */
export class BackendService {
	apiURL = 'http://api.recipebuddy.xyz:8888'

	constructor( private http: HttpClient)
	{
	}

	httpOptions = {headers: new HttpHeaders(
		{'Content-Type':'application/json'}
	)}


	getRecipes(): Observable<number[]>
	{
		return this.http.get<MsgList>(this.apiURL + '/recipes')
			.pipe (
				retry(1),
				map(msg => msg.Data),
				catchError(this.handleError)
			)
	}

	handleError(error) {
		let errMsg = '';
		if (error.error instanceof ErrorEvent) {
			errMsg = error.error.message;
		} else {
			errMsg = 'Error API';
		}
		console.log(errMsg)
		window.alert(errMsg)
		return throwError(errMsg);
	}
}