我对在Angular 5中使用httpclient感到困惑。我是Angular的新手,只是按照官方Angular教程进行操作。我不太了解observables、promise、pipe等等。目前,我正在使用一个服务来处理所有的http方法。对于post请求,我正在使用pipe。以下是该方法。
create(model: any,URI) :Observable<Object>{
return this.http.post(API_URL+URI, model)
.pipe(
catchError(this.handleError('create', model))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error("default"+error); // log to console instead
var errors=error["error"];
var type=errors.errors;
this.log(`${operation} failed: ${JSON.stringify(errors.errors)}`);
return of(result as T);
};
}
private log(message: string) {
this.messageService.add('DataService: ' + message);
}
在组件内部,我像这样调用了create方法..
onSubmit() {
this.loading = true;
this._dataService.create(this.model,companytype_url).subscribe(data => {
console.log("inside component data type-company"+JSON.stringify(data));
},
error=>{
var error_data=JSON.stringify(error);
console.log("inside component error type-company ->" + error_data)
}
);
this.submitted = true;
this.loading = false;
this.companytypeForm.reset();
}
我应该在组件中使用subscribe吗?我需要一个通用的http类来处理所有的api请求。这是一个大型应用程序,有很多组件。由于我是Angular的新手,对调用http方法的不同方式感到困惑。