HTTP 获取调用 Angular 6

HTTP get call in Angular 6

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

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

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

你在 angular 6 中调用 http 的方式是 correct.Though 我正在分享代码片段,请记住,就像我们可以在管道和所有 returns Observable object.So 你不需要显式地将这个运算符输出转换成 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.if 您想要 httpClient 的答案然后请 post 您的问题分开。

希望对您有所帮助