1 minute read

Angular Promise Example

Time to examine promises' use inAngular development. WithAngular CLI, we will start by building a straightforwardAngular application.

ng new angular-promise-example –routing=false –style=css

Advertisement

By using this command, a fresh Angular application will be created with no routing and a CSS stylesheet format.To sendAPI queries to web servers to produce or fetch data, we will next configure HttpClient.

Since you must always wait a certain length of time before receiving the requested data, fetching data is a typical asynchronous process. HttpClient can be used inAngular programming to fetch data.

We'll show how to use JavaScript/ES6 Promises in place of RxJS Observables, which are how HttpClient handles asynchronous operations.

In the app/app.module.ts file of your project, add the following changes:

Next, open the src/app/app.component.ts file and add the following code to send a HTTP request and process the response using a Promise inAngular.

We import HttpClient and inject it via the component constructor and use it to send the HTTPrequest.

Next, we call the get() method to send the request and the toPromise() method to convert the returned RxJS Observable to a promise.

In the ngOnInit() life-cycle method, we send the actual request by calling the then() method of the promise as follows:

If the promise is resolved successfully we simply output the data in the console and in case of an error we display the error.

Conclusion

I trust that now you have a good understanding of what Promise in Angular development is. In addition, we saw the ES6-introduced JavaScript Promises concept. JavaScript promises that can be specifically incorporated into the application have been put into practice. Also, we came upon the Angular application example of constructing a promise. Nonetheless, Angular is the greatest and most popular choice if you have any questions about developing web applications. It enables you to create applications for various business sectors.

This article is from: