Joh*_*eer 5 typescript angular angular-httpclient angular6
我将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;
});
Run Code Online (Sandbox Code Playgroud)
这就是我现在正在做的事情.这是应该如何在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.');
};
Run Code Online (Sandbox Code Playgroud)
你在角度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;
}));
Run Code Online (Sandbox Code Playgroud)
您也可以使用HttpClient.如果您想要httpClient的答案,那么请分开发布您的问题.
希望对你有帮助
| 归档时间: |
|
| 查看次数: |
15456 次 |
| 最近记录: |