typescript Angular 6 中的 HTTP 获取调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50759725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:28:17  来源:igfitidea点击:

HTTP get call in Angular 6

angulartypescriptangular6angular-httpclient

提问by Johannes Schweer

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:

我将我的 Angular 项目更新为 Angular 6,但不知道如何执行 http get 请求。这就是我在 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?

这就是我现在的做法。在 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.');
};

回答by Prasanna Sasne

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.

您在 angular 6 中调用 http 的方式是正确的。虽然我正在共享代码片段,但请记住,我们可以在管道内传递操作符的数量,并且所有操作符都返回 Observable 对象。所以您不需要显式地隐藏这个操作符输出到 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.

您也可以使用 HttpClient。如果您想要 httpClient 的答案,请单独发布您的问题。

Hope this will help you

希望能帮到你

回答by Gleycer Parra

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

这是一个示例,但您可以在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')
        });
}