Last active
February 13, 2022 07:33
-
-
Save surajmandalcell/ec19232e624f64f91a8febdb2cafa657 to your computer and use it in GitHub Desktop.
Angular observable mock & error handling utils to shift from direct api to mock data when developing(for legacy code)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpErrorResponse } from '@angular/common/http'; | |
import { throwError } from 'rxjs/internal/observable/throwError'; | |
export function errorHandler(error: HttpErrorResponse) { | |
return throwError(error); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inside service | |
apiCall(data: any) { | |
this.getHearder(); | |
if (environment.production) { | |
return this.http | |
.post<any>(this.baseUrl, data, this.httpOptions) | |
.pipe(catchError(errorHandler)); | |
} | |
else { | |
return obsMock(keywordOverviewMock); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable } from 'rxjs'; | |
export function obsMock(data: any, time: number = 1000) { | |
return new Observable((subscriber) => { | |
setTimeout(() => { | |
subscriber.next(data); | |
subscriber.complete(); | |
}, time); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment