We can use this returned result for showing appropriate message to use if required. We will use thedifferent methods like get(), post(), put() and delete() of Http to perform CRUD operations of product.
But now we have converted addProduct() method into an asynchronous method which returns an observable. theIn-memory Web APImodule has nothing to do with HTTP in Angular.
If you are usingAngular 2 or 4, read HTTP Calling using Angular 2 or 4. We can control the visibility of the loader by using one loader service. HttpClient.getreturns thebodyof the response as an untyped JSON object by default. Thats why we will set the HttpHeaders'Content-Type' as 'application/json'. This particularHttpClient.getcall returns anObservable
Here, we will use Angular 5 to perform HTTP calls. Replace the removeProduct() methodin ProductService with below code. once web services available from the remote server, you just need to change the URL in Http calls. Now inject HttpClientinto the constructor of ProductService in a private property calledhttpClient.
so lets first create LoaderComponent, using below CLI command. So add the LoaderServiceusing below CLI command in /service folder, Now add the following code in the LoaderService. We will replace the getProduct() method in ProductService with below code. It may also be convenient in the early stages of your own app development when the servers web API is not yet implemented. So if you run the application you will get the error on a console as : Cannot read property productType of undefined. You make a request, it returns a single response. We can get the product id directly as a number or by getting the product object. (elvis operator) in product.productType as product?.productType, so that template will access the productType only when a product is not undefined. The advantage of simulated data server is, you can start your front end application development without waiting for the web service from the remote web server. we will use HttpClient service of @angular/common/httplibrary for HTTP calls. HTTP service call takes some time to get response, So in this delay instead of showing blank space, we can show loader or message to the user. You can see in a console of the browser that it prints products fetched message and array of product. We will mimiccommunication with a remote data server by using theIn-memory Web APImodule. You wont have to set up a server to learn aboutHttpClient. After reporting the error to console, the handler returns a safe value to the app so it can keep working.
Get Product by id : getProduct(id) method, Awesome Charts in Angular 13 with ng2-charts, Client-Side PDF Generation In Angular 13 With PDFMake, Dynamically Add Title and Meta Tags on Route Change in Angular, Integrate Google Analytics with Angular | Angular SEO, It constructs a request URL with the desired products. In practice, it will only return a single product array. Instead of handling the error directly, it returns anerror handlerfunction tocatchErrorthat it has configured with both the name of the operation that failed and a safe return value. Now refresh the browser and check all the functionality.
AllHttpClientmethods return a RxJSObservableof something. Here, the simulated server returns an Observable, which is successfully added. It passes the error to an error handlerthat can do what it wants with the error. To catch errors in ProductService.getProducts() method, we pipe the observable result from http.get() through an RxJS catchError() operator.
Define theproductsUrl with the address of the products resource on the server. In this tutorial, we will add the data persistence features in our application with the help of Http Services of Angular.
To resolve this issue, add ?
So to callremoveProduct()method we need tosubscribeit inProductsComponent, so replace the deleteProduct() method of ProductsComponent as shown below.
So to call getProduct() method we need to subscribe it in AppProductModelComponent as shown below, In above code, we will navigate to products view only when we get the successful result from the addProduct() method of product.service.ts.
This facility is a great convenience for the tutorial.
to control the visibility of LoaderCompnent we will create LoaderService, which can be used by any other component. HTTP is a request/response protocol. Here we will get the JSON object of Product Array.
Import HttpClient and HttpHeadersfrom @angular/common/http in the ProductService. We dont have any web services for our application, we can create web services as I talked above, but instead of creating web services, we can simulate a data server, which work same as other web services. Because each service method returns a different kind ofObservableresult,handleError()takes a type parameter so it can return the safe value as the type that the app expects. When your server is ready, detach theIn-memory Web API, and the apps requests will go through to the server. This configurationreplaces the mock-product-data.ts, which is now safe to delete. You can create Web Service in any language like Java, PHP, .Net or NodeJS. Applying the optional type specifier,
In general, anObservablecanreturn multiple values over time. The server should respond with a single product rather than an array of products. TheforRoot()configuration method takes anInMemoryProductServiceclass that primes the in-memory database. For the testing purpose, we can also generate the delay in a simulated sever, while performing HTTP calls, by delay property in options of forRoor(), as shown below. As shown below. We have swappedhttpClient.getforofand the app keeps working without any other changes because both functions return anObservable
In our simulated data server, we can add the product by passing product object in post call of api/products, Replace the addProduct(product) method with below code. But now we have convertedremoveProduct()method into an asynchronous method which returns an observable. Things go wrong,when we are getting data from the remote data server, so we need to catch this errors and do something appropriate. Till now, we are getting the dummy products data from MockData.Products. Now, Import the HttpClientInMemoryWebApiModuleand theInMemoryProductService in the AppModule, Add theHttpClinetInMemoryWebApiModuleto the@NgModule.importsarray and configureit with theInMemoryProductService, as shown below.
We will do that with the RxJStapoperator, whichlooksat the observable values, doessomethingwith those values, and passes them along.
Here we will create one LoaderComponentin LayoutModule which we can use to display loader for all the views.
We have created loaderService public, so that we can access it on the template of LoaderComponent.
Our current In Memory Web APIURL is api/products; define productsUrl as below. I have added *ngIf directive, which will make the loader visible only when loaderService.visible is true. If you are using Angular 2 or 4 and working with Http class of @angular/http (deprecated in Angular 5), then you need to convert response data into JSON object. https://github.com/ngdevelop-tech/electronic-shop, Get Product by id : getProduct(id) method, Cannot read property productType of undefined. Here is the final version ofgetProducts() with thetapoperator.
Now refresh the page, you will able to see the loader. Note: we are using getProduct() method in product-detail.component.ts, because we have set the delay for the testing purpose, initially product object of product-detail.component.ts will be undefined. We need to display the loader only when the HTTP call is in progress, once HTTP call is complete we need to hide the loader. Now in whenever you want to make loader visible, use the showLoader() method of LoaderService and hide the loader by using hideLoader(). The shape of the JSON data is determined by the servers data API. We can pass the headers to Http Service using HttpHeaders class of @angular/common/http library. We can either use loading GIF or rotating icons to display loader. To makeHttpClientavailable everywhere in the app. So lets start the first step is to enable HTTP services. HTTP services is the important part of any application which communicates with the server. Note:In a previous chapter, we have not convertedremoveProduct()method into an asynchronous method, so inProductsComponent, we are still using synchronous calling ofremoveProduct()method.
Most web APIs support aget by idrequest in the formapi/products/:id(such asapi/products/11). We can consume this web service using HttpClient in an angular app. In this method, we are passing the product in the JSON format.
Now we will extend the observable result with the.pipe()method and give it acatchError()operator. Now we require remote data server which provides HTTP Web Service, which we can call using Angular Front End. To get the multiple types of the same parameter we will use product: Product | number, Http Web Service Calling using HttpClient, Simulate a Data Server using In Memory Web Api, HttpClient get(), post(), put() and delete() methods. We will import thecatchErrorsymbol fromrxjs/operators, along with some other operators we will need later. After installing the module, the app will make requests to and receive responses from theHttpClientwithout knowing that theIn-memory Web APIis intercepting those requests, applying them to an in-memory data store, and returning simulated responses. We are not discussing InMemoryWebApi Module in detail, for more information refer README.md of In Memory Web Api module. the URL is the products resource URL plus theidof the product to delete. ThecatchError()operator intercepts anObservablethat failed. We can process the result before we return the result to calling component method. Angular provides @angular/common/http library for communicating with a remote server over HTTP. Note: Because I have put the delay of 2 seconds, in InMemoryProductService, you will see the result after 2 seconds. AnObservablefromHttpClient always emits a single value and then completes, never to emit again. Note: we need to export LoaderComponent from the LayoutModule, to use it outside the LayoutModule. Now lets get the products from the data server.
The same way we will update the AddProductTemplateComponent. We will call Http Web Services (REST Services) using HttpClient. httpClient.post(this.productsUrl, product, httpOptions), will pass product object in the body of post call , and send the Headers in the httpOptions. InProductServicemethods, we willtapinto the flow of observable values and send a message viaconsole.logorwe can use the loggers library to maintain logs.
Note: In a previous chapter, we have not converted addProduct() method into an asynchronous method, so in AddProductModelComponent, we are still using synchronous calling of addProduct() method. Thetapcall back doesnt touch the values themselves. handleError() error handler will be shared by manyProductServicemethods so its generalized to meet their different needs. Check here to see How to work with HTTP calling in Angular 2 or 4? Execute below command in terminal to Install theIn-memory Web APIpackage, Once successfully installed, create an InMemoryProductService innew file called.
We are using this only to simulate our remote server, if you have remote services available, then you can directly use that web service also. Most front-end applications communicate with backend services over the HTTP protocol. Replace the loader.component.html as below. By using res.json() method. There are three significant differences fromgetProducts(). Now add the following code in loader.component.html, To display loader on page, we will add the