HTTP get call in Angular 6
Asked Answered
E

2

5

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.');
};
Ethic answered 8/6, 2018 at 11:32 Comment(14)
whats the pipe for?Asphyxiant
@Asphyxiant - pipe used to combine all rxjs realted operators ...Silurian
what is you question , code seems correctSilurian
youd dont need the rxjs operators if youre using the http client, its pretty much built in nowAsphyxiant
@Asphyxiant - are you kidding ?, its needed to catch error , share observableSilurian
you need it for the catch, but not for a map or anything anymoreAsphyxiant
"is that how it is supposed to do" - does it work?Gershon
What is this.http? HttpClient or Http ?Athematic
The Question is: "Is this best practice? Or is there a better way in Angular 6?"Ethic
@Athematic it is HttpClientEthic
@Athematic it has to be httpclient as http is deprecated in 5 and im pretty sure its removed in 6Asphyxiant
Yes it's removed, that's why I asked. @Asphyxiant OP hasn't stated if his code is working or notAthematic
I did not test the new code. I just wanted to know if I got the code right.Ethic
Follow this URL, it has steps how to use HttpClient. angular.io/guide/httpOverside
E
6

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

Encephalo answered 16/7, 2018 at 9:50 Comment(1)
The first line is incomplete, please update it... , says import Http from angular but where from angular ?Guthrey
S
1

This is an example, but you can get more info in https://angular.io/guide/http:

getByEmail(email): Observable<void> {   
    const endpoint = API_URL + `/api/datos_privados/email/${email}`;
    return this.httpClient.get<void>(endpoint,
        {
            headers: new HttpHeaders()
                .set('Accept', 'aplication/json')
        });
}
Selia answered 12/6, 2018 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.