|
| 1 | +import { Injectable } from '@angular/core' |
| 2 | +import { HttpClient } from '@angular/common/http' |
| 3 | +import { MatSnackBar } from '@angular/material/snack-bar' |
| 4 | +import { Observable, of } from 'rxjs' |
| 5 | +import { tap, catchError } from 'rxjs/operators' |
| 6 | +import { environment } from '../../../environments/environment' |
| 7 | +import { Promocode } from './promocode.model' |
| 8 | +import { SponsorService } from '../sponsors/sponsor.service' |
| 9 | + |
| 10 | +@Injectable() |
| 11 | +export class PromocodeService { |
| 12 | + private promocodeUrl = environment.cannonUrl + '/promo-code' |
| 13 | + private promocodes: Promocode[] |
| 14 | + |
| 15 | + constructor( |
| 16 | + private http: HttpClient, |
| 17 | + private snackBar: MatSnackBar, |
| 18 | + private sponsorService: SponsorService |
| 19 | + ) { } |
| 20 | + |
| 21 | + getPromocodes(eventId: string): Observable<Promocode[]> { |
| 22 | + if (this.promocodes) { |
| 23 | + return of(this.promocodes) |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | + return this.http.get<Promocode[]>(this.promocodeUrl).pipe( |
| 28 | + tap(promocodes => this.sponsorService.getSponsors(eventId).subscribe(sponsors => { |
| 29 | + this.promocodes = promocodes.map(promocode => { |
| 30 | + const sponsor = sponsors.find(sponsor => sponsor.id === promocode.company) |
| 31 | + promocode.company = sponsor |
| 32 | + promocode.link = this.isLink(promocode.code) |
| 33 | + return promocode |
| 34 | + }) |
| 35 | + })), |
| 36 | + catchError(this.handleError<Promocode[]>('getPromocodes', [])) |
| 37 | + ) |
| 38 | + } |
| 39 | + |
| 40 | + isLink(code: string): boolean { |
| 41 | + return code.startsWith('http://') || code.startsWith('https://') |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Handle Http operation that failed. |
| 46 | + * Let the app continue. |
| 47 | + * @param operation - name of the operation that failed |
| 48 | + * @param result - optional value to return as the observable result |
| 49 | + */ |
| 50 | + private handleError<T>(operation = 'operation', result?: T) { |
| 51 | + return (error: any): Observable<T> => { |
| 52 | + // this.snackBar.open(error.message, "Ok", { |
| 53 | + // panelClass: ['mat-toolbar', 'mat-warn'], |
| 54 | + // duration: 2000 |
| 55 | + // }) |
| 56 | + |
| 57 | + this.snackBar.open("An error occurred and was sent to SINFO team.", "Ok", { |
| 58 | + panelClass: ['mat-toolbar', 'mat-warn'], |
| 59 | + duration: 2000 |
| 60 | + }) |
| 61 | + |
| 62 | + // Let the app keep running by returning an empty result. |
| 63 | + return of(result) |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments