在Angular 5 http请求中使用observable有什么好处? [英] What is the benefit of using observable in Angular 5 http requests?
问题描述
我对在angular 5中使用httpclient感到困惑.我是angular的新手,只是遵循官方的angular教程.我对可观察对象,承诺,管道等不了解很多.目前我有一个用于处理所有http的服务对于发布请求,我正在使用pipe.下面是方法.
I am confused about using httpclient in angular 5.I am new to angular and just following the official angular tutorial.I dont know much about observables,promise,pipe etc..Currently I am having a service for handling all the http methods.For post request I am using with pipe.Below is the method.
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方法.
And inside the component I am calling this create method like this..
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();
}
我应该在组件中使用订阅吗?我需要一个通用的http类来处理所有api请求.这是一个很大的应用程序,并且有很多组件.由于我是Angular的新手,所以我对调用http方法的不同方法感到困惑.
Should I use subscribe in component? I need a general http class to handle the all the api requests.It is a big application and there are a lot of components.Since I am new to Angular I am confused about the different ways of calling http methods.
推荐答案
我应该在组件中使用订阅吗?
Should I use subscribe in component?
是的.如果您不订阅,则什么都不会发送到服务器
Yes. If you don't subscribe, nothing will be sent to the server
我需要一个通用的http类来处理所有api请求
I need a general http class to handle the all the api requests
这就是HttpClient.如果您的服务是完全通用的,它将不会在HttpClient已经提供的内容中添加任何内容.使用专用的服务,这些服务实际上提供了更高级别的抽象:具有类型化的参数,必要的输入转换,使用适当的URL,返回类型化的对象,知道如何转换响应等.
That's what HttpClient is. If your service is completely generic, it won't add anything to what HttpClient already provides. Use dedicated services, which actually provide a higher-level abstraction: have typed arguments, transform inputs necessary, use the appropriate URL, return typed objects, know how to transform the response, etc.
由于我是Angular的新手,所以我对调用http方法的不同方式感到困惑.
Since I am new to Angular I am confused about the different ways of calling http methods.
这就是Angular提供...文档的原因.例如,此 HttpClient指南,以及此
That's why Angular provides... documentation. For example, this HttpClient guide, and this RxJS guide. Read them.
这篇关于在Angular 5 http请求中使用observable有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!