HTTP get call in Angular 6

点点圈 提交于 2019-12-10 14:05:10

问题


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.');
};

回答1:


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




回答2:


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')
        });
}


来源:https://stackoverflow.com/questions/50759725/http-get-call-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!