-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmovie.service.ts
More file actions
84 lines (71 loc) · 2.42 KB
/
movie.service.ts
File metadata and controls
84 lines (71 loc) · 2.42 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { Injectable } from '@angular/core';
import { MockMovies } from './mock-movies';
import { HttpClient } from '@angular/common/http';
import { TMDBResponse, TMDBMovie, TMDBSingleResponse } from './tmdb-result';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { Movie } from '../movies/movie';
import { tap, catchError } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root',
})
export class MovieService {
constructor(
private http: HttpClient,
private storage: LocalStorageService,
private toastr: ToastrService
) {}
findMovie(query: string) {
return this.http.get<TMDBResponse>(
'https://api.themoviedb.org/3/search/movie?api_key=b57b192257e7e93c636c59c8ccd2d366&language=en-US&page=1&include_adult=false&query=' +
query
);
}
getById(id: number) {
return this.http
.get<TMDBSingleResponse>(
`https://api.themoviedb.org/3/movie/${id}?api_key=b57b192257e7e93c636c59c8ccd2d366&language=en-US`
)
.pipe(
tap((_) => console.log(`fetched tmdbSingleResponse id=${id}`)),
catchError(this.handleError<TMDBSingleResponse>(`getMovieDetail ${id}`))
);
}
getMovies(): Movie[] {
try {
return this.storage.retrieve('collection') || [];
} catch (error) {}
}
removeFromCollectionById(id: number) {
try {
const collection = this.storage.retrieve('collection') || [];
const updatedCollection = collection.filter((m) => m.tmdbId !== id);
this.storage.store('collection', updatedCollection);
this.toastr.success(`Movie removed`);
} catch (error) {
this.toastr.warning(`Movie could not be removed from collection`);
}
}
addToCollection(movie: TMDBMovie) {
try {
const collection = this.storage.retrieve('collection') || [];
collection.push({
title: movie.title,
year: movie.release_date,
posterPath: movie.poster_path,
backdropPath: movie.backdrop_path,
overview: movie.overview,
tmdbId: movie.id,
});
this.storage.store('collection', collection);
} catch (error) {}
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
this.toastr.warning(`${operation} failed: ${error.message}`);
return of(result as T);
};
}
}