Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP get call in Angular 6

I updated my Angular project to Angular 6 and don't know how to do http get requests. Thats how I did it in Angular 5:

get(chessId: string): Observable<string> {

this.loadingPanelService.text = 'Loading...';
this.loadingPanelService.isLoading = true;

const url = `${this.apiPathService.getbaseUrl()}api/chess/${chessId}/rating`;   

return this.http.get<string>(url)
.catch((error) => {
    console.error('API error: ', error);

    this.loadingPanelService.isLoading = false;
    this.notificationService.showErrorMessage(error.message);

    return Observable.of(null);
  })
  .share()
  .finally(() => {
    this.loadingPanelService.isLoading = false;
  });

And this is how I'm doing it now. Is that how it is supposed to be done in Angular 6?

...
return this.http.get<string>(url)
.pipe(
  catchError(this.handleError),
  share(),
  finalize(() =>{this.loadingPanelService.isLoading = false})
);

private handleError(error: HttpErrorResponse) {
console.error('API error: ', error);

this.loadingPanelService.isLoading = false;
this.notificationService.showErrorMessage(error.message);

// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
};
like image 938
Johannes Schweer Avatar asked Jun 08 '18 11:06

Johannes Schweer


1 Answers

The way you are calling http in angular 6 is correct.Though i'm sharing code snippet, just keep in mind like we can pass number of operators inside pipe and all returns Observable object.So you don't need to explicitly covert this operator output into Observable.

import { Http, Response } from '@angular/http'
import { throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

.....
 return this.http.get(url)
    .pipe(map((response : Response) => {
        return response.json();   
    }), catchError((error: Response) =>{
        this.loadingPanelService.isLoading = false;
        this.notificationService.showErrorMessage(error.message);
        return throwError('Something went wrong');      
    }), finalize(() => {
        this.loadingPanelService.isLoading = false;
    }));

You can also use HttpClient.if you want answer for httpClient then please post your question seperatly.

Hope this will help you

like image 111
Prasanna Avatar answered Sep 23 '22 09:09

Prasanna