Angular 6中的HTTP get调用 [英] HTTP get call in Angular 6

查看:169
本文介绍了Angular 6中的HTTP get调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Angular项目更新为Angular 6,但不知道如何处理http获取请求.那就是我在Angular 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;
  });

这就是我现在的做法.那是应该在Angular 6中完成的吗?

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

推荐答案

在angular 6中调用http的方式是正确的.尽管我共享代码段,但请记住,就像我们可以在管道内传递多个运算符并全部返回Observable对象.因此,您无需将此运算符的输出显式转换为Observable.

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

您也可以使用HttpClient.如果您想为httpClient回答,请分别发布问题.

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

希望这对您有帮助

这篇关于Angular 6中的HTTP get调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆