What is the benefit of using observable in Angular 5 http requests?

只谈情不闲聊 提交于 2021-02-19 05:12:18

问题


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

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();
    }

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.


回答1:


Should I use subscribe in component?

Yes. If you don't subscribe, nothing will be sent to the server

I need a general http class to handle the all the api requests

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.

Since I am new to Angular I am confused about the different ways of calling http methods.

That's why Angular provides... documentation. For example, this HttpClient guide, and this RxJS guide. Read them.



来源:https://stackoverflow.com/questions/49885335/what-is-the-benefit-of-using-observable-in-angular-5-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!