我将Angular项目更新为Angular 6并且不知道如何进行http获取请求。这就是我在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.');
};
答案 0 :(得分:6)
在角度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;
}));
您还可以使用HttpClient。如果您想为httpClient回答,请分别发布您的问题。
希望这对您有帮助
答案 1 :(得分:0)
这是一个示例,但您可以在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')
});
}