What is Promise in Angular Development?

JavaScript is a programming language created to add interactivity to web pages. However, in JavaScript coding, the developers find it quite challenging to deal with the callback functions. The reason is that they must deal with asynchronous events when users interact with a web page.

Such callback functions became a pain for many developers, especially when building complex and rich apps with JavaScript for modern browsers. To overcome such complexity, ES6 introduced Promises, a modern and powerful abstraction for writing asynchronous code in a better and easily maintainable way.

In this article, you’ll learn about what is Promise in Angular application and will come across the concept of JavaScript Promises introduced in ES6.

What is Promise in JavaScript?

A promise is a JavaScript or TypeScript object that may produce a value at some point in time. A promise may be in one of 4 possible states:

  • fulfilled – The action relating to the promise succeeded
  • rejected – The action relating to the promise failed just because an error occurs during promise implementation
  • pending – It’s an initial state that hasn’t fulfilled or rejected yet
  • settled – Has fulfilled or rejected

Get Custom-Tailored Web App Development Solutions For Your Business Needs

We strictly adhere to the standard software development lifecycle to provide the best possible IT solutions for your business success.

How To Create a Promise in JavaScript?

Let’s highlight a simple example of creating a promise in plain JavaScript.

Copy
var promise = new Promise((resolve, reject) => {
  resolve("Promise Resolved"); 
})

promise.then((success) => { 
  console.log(success);
})
.catch(function(error) => {
  console.log(error);
}); 
// Output: Promise Resolved

The developers from the leading AngularJS development company implements Promises by calling the then() and catch() methods.

  • then() method: It takes two callback functions as parameters and is invoked when a promise is either resolved or rejected.
  • catch() method: It takes one callback function and is invoked when an error occurs.

Now, let us understand the basic concept of “what is Promise in Angular?”

Related Post: Angular Resolver

What is Promise in Angular?

When the AngularJS developers are dealing with asynchronous operations like an HTTP request, they are not sure of the exact time to get a response from the server. By default, Javascript is a programming language that is

  • Synchronous;
  • Blocking; and
  • Single-threaded language.

In simple words, we can say that the Javascript engine can process only one code at a time in a single thread. So, when a thread is blocked, we can’t execute other code that is also blocked, making JS slow and unable to perform multiple operations.

On the other hand, the asynchronous operation is solely responsible for making code nonblocking. It means that it allows the developers to execute multiple codes at the same time.
In the Angular framework, the developers can quickly achieve asynchronous by utilising the following method.

  • The Callback function
  • The Promise from Javascript can be used in Angular.
  • Observable using Rxjs library in Angular: Library for reactive programming using Observables.

You may also like to read: What is Angular?

Moreover, while dealing with an asynchronous operation, the developers can quickly move the code to the following line by allowing UI remains responsive. The user continues working on the application while asynchronous operations like HTTP requests are processed in the background.

Now the concept of Promise in Angular comes into the picture. The Promise in Javascript is nothing but a piece of task that is wrapped in asynchronous operation and notified whenever the asynchronous process is completed or failed at some point in the future.

Two possible outcomes occur when the developer runs the Promise: The Promise is completed or failed. With the help of the async and await keyword with Promise, it becomes easy for the developers to deal with easy to read, write, and we can also use “try and catch” for error handling with (async & await).

Planning To Develop a Robust Single-Page Application?

Albiorix is a leading AngularJS Development Company having core expertise in designing and building feature-rich applications for all your business needs.

Angular Promise Example

Its time to see how to use promises in Angular development First, we will create a simple Angular application using Angular CLI.

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

This command will create a new Angular application with no routing and CSS for stylesheet format. Next, we will set up HttpClient to send API requests to web servers to create or fetch data.

Fetching data is a standard asynchronous operation as you always have to wait for an amount of time to receive the requested data. In Angular development, you can use HttpClient for fetching data.

HttpClient uses RxJS Observables to handle asynchronous operations; let’s see how to use JavaScript/ES6 Promises instead.

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

Copy
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule }  from '@angular/common/http';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HttpClientModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

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

Copy
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "Angular Application and Promises Example";API_KEY = "e40d07f00b094602953cc3bf8537477e";

constructor(private httpClient: HttpClient) {}

ngOnInit() {
console.log("Angular Promises");
this.fetchDataAsPromise()
.then((data) => {
console.log(JSON.stringify(data));
})
.catch((error) => {
console.log("Promise rejected with " + JSON.stringify(error));
});
}

fetchDataAsPromise() {
return this.httpClient
.get(
`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
)
.toPromise();
}
}

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

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

Copy
fetchDataAsPromise() {
return this.httpClient
.get(
`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
)
.toPromise();
}

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

Copy
this.fetchDataAsPromise()
.then((data) => {
console.log(JSON.stringify(data));
})
.catch((error) => {
console.log("Promise rejected with " + JSON.stringify(error));
});

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

Related Post: Angular Promise Vs Observable

Conclusion

So, I hope you got a clear vision on what is Promise in Angular development is. In addition, we came across the concept of JavaScript Promises introduced in ES6. We have seen the implementation of JavaScript promises that can be specifically included in the application.

In addition, we came across the example of creating a promise in the Angular application. Still, if you have any query related to web application development, Angular is the best and leading option that help you build applications for all business verticals.

What’s New in Node.js 19? Features & Updates That You Must Know

Node.js 19 is now live!

And I know you’re too much excited to know the features and major updates that are introduced in Node.js 19.

If you ask me about what’s exciting about Node.js 19, then I must say that you can expect new releases approximately every two weeks. Since this is an odd-numbered release line, Node version 19 will not be promoted to LTS. Let’s move ahead with your question about what’s new in Node.js 19.

Overview of Node.js 19

With the release of Node.js 19 in the market, a big convenience for Node.js developers came where they can easily deal with early feature testing.

Some of the key highlights that are introduced with Node.js 19 include the update of the V8 JavaScript engine to 10.7 and HTTP(s)/1.1 KeepAlive enabled by default.

Node.js 19 will effectively become the “Current” release line and is going to replace Node.js 18 definitely when it enters long-term support (LTS). So, till then, Node.js 19 will officially be the ‘Current’ release for the next six months, until April 2023.

Build High-Performance Web Apps Using Our Node.js Web Development Solutions

We help you build Node.js development services to build real-time, function-rich, scalable web applications for all your business needs.

What are the Updates on Node.js 19?

Node.js is going to benefit you in many ways especially for dealing with back-end development services. It’s time to explore the major updates that have been introduced the Node.js 19 version.

  1. node –watch (experimental)

    Support for running in “watch” mode using the node —watch option is an intriguing new feature recently added to the runtime. It will restart when an imported file is updated while your application is running in “watch” mode.

    $ node –watch index.js

    This feature is available in v19.0.0 and v18.11.0+.

    Let’s explore this feature with an example.

    In our server/index.js:

    Copy
    const express = require("express");
    const path = require("path");
    const app = express();
    app.use(express.static(path.join(__dirname, "../build")));
    
    app.listen(8080, () =>
      console.log("Express server is running on localhost:8080")
    );
    

    So, we were using a nodemon tool to run the server and to make instant file changes whenever we restarted our application. We were using the “nodemon server” command to apply the effect for the same.

    Now, with the release of node.js 19, you do not need to type such a command or install the additional tool. Instead, just execute the command “node –watch” to automatically restart the application when file changes are detected.

    Copy
    % node --watch server
    (node:67643) ExperimentalWarning: Watch mode is an experimental feature. 
    This feature could change at any time
    (Use `node --trace-warnings ...` to show where the warning was 
    created)
    Express server is running on localhost:8080
    
  2. HTTP(S)/1.1 KeepAlive by default

    Node.js 19 sets keepAlive to true by default. This means that any outgoing HTTP(s) connection will automatically use HTTP 1.1 keepAlive. The default keepAlive duration is 5 seconds.

    If we consider the same example,

    Copy
    const http = require('node:http');
    console.log(http.globalAgent);
    const https = require('node:https');
    console.log(https.globalAgent);
    

    And if we use Node.js 16 to run the file using the command “nvm use 16”, you’ll see that HTTP.globalAgent and HTTPS.globalAgent set keepAlive false.

    But that’s not the case with Node.js 19. If you execute the server with “nvm use 19”, the output goes something like this.

    • HTTP.globalAgent sets keepAlive true, and the default keepAlive duration is 5 seconds (5000 ms).
    • HTTPS.globalAgent sets keepAlive true, and the default keepAlive duration is 5 seconds (5000 ms).

    Keeping keepAlive to true will generally deliver better throughput as connections are reused by default.

  3. Stable WebCrypto

    The WebCrypto API is a feature-rich interface that helps you build systems using cryptography. With node.js 19, the WebCrypto API is stable (by excluding the algorithms: Ed25519, Ed448, X25519, and X448).

    To access this module, you can use globalThis.crypto or require(‘node:crypto’).webcrypto. Let’s go through an example where we will perform a number of low-level cryptographic functions:

    Copy
    const { subtle } = globalThis.crypto;
    
    (async function() {
    
      const key = await subtle.generateKey({
        name: 'HMAC',
        hash: 'SHA-256',
        length: 256
      }, true, ['sign', 'verify']);
    
      console.log('key =', key);
    
      const enc = new TextEncoder();
      const message = enc.encode('I love cupcakes');
    
      console.log('message =', message);
    
      const digest = await subtle.sign({
        name: 'HMAC'
      }, key, message);
    
     console.log('digest =', digest);
    
    })();
    
    

    (The above code is taken from GitHub)

    If you run the server, the output goes like this.

    Copy
    % node server
    key = CryptoKey {
      type: 'secret',
      extractable: true,
      algorithm: { name: 'HMAC', length: 256, hash: [Object] },
      usages: [ 'sign', 'verify' ]
    }
    message = Uint8Array(15) [
       73, 32, 108, 111, 118,
      101, 32,  99, 117, 112,
       99, 97, 107, 101, 115
    ]
    digest = ArrayBuffer {
      [Uint8Contents]: <30 01 7a 5c d9 e2 82 55 6b 55 90 4f 1d de 36 d7 89 dd fb fb 1a 9e a0 cc 5d d8 49 13 38 2f d1 bc>,
      byteLength: 32
    }
    
    
  4. Custom ESM Resolution Adjustments

    Node.js has removed the –experimental-specifier-resolution flag. Its functionality can now be achieved via custom loaders.

  5. Dropped DTrace/SystemTap/ETW Support

    For the following two reasons, Node.js has dropped the support for DTrace/SystemTap/ETW:

    • There are no clear indicators anyone is using DTrace, SystemTap, or ETW.
    • The complexity of maintaining and supporting these tools has proved not worth the effort.
  6. V8 JavaScript engine is updated to V8 10.7

    Node.js 19 has updated the V8 JavaScript engine to V8 10.7, which includes a new function, Intl.NumberFormat, for language-sensitive number formatting.

    Intl.NumberFormat(locales, options)

    locales is an optional parameter, which is a BCP 47 language tag or an array of such strings.

    These are the major changes that have been introduced in Node.js version 19. If you need any help regarding Node.js installation or upgradation, hire Node.js developers on part-time or full-time basis.

Upgrade to Node.js 19 Now!

What are you waiting for?

Go ahead and download Node.js 19.0.0 today.

Being a Node.js development company Australia, we have a team of expert Node.js developers for hire who are proficient in dealing with application testing and modules in the Node.js 19 version. And yes, by selecting Node.js as your preferred technology for your project needs, you can efficiently build responsive web apps.

find the release post of Node v19.0.0 (Current) which contains the full list of commits included in this release.

What’s New in Angular 14? Important Features and Examples

Angular 14, a new version of the TypeScript-based web application framework, angular 14 release date is 2nd June 2022. Prior to the previous versions of Angular 13, Angular 14 is considered to be the systematic pre-planned upgrade of Angular.

Web app development is made easy and quick with the introduction of new Angular 14 features like stand-alone components, which eliminates the use of ng modules.

It’s just short information about what’s new in Angular 14. We have come up with detailed information and examples to make it easy for the AngularJS developer to deal with Angular development.

Angular 14 Features

As we all are aware of what is Angular, it’s time to explore the Angular 14 features introduced officially by the Angular development community.

angular 14 features

  1. Standalone Components

    The components are not dependent on any other components and are referred to as Angular 14 standalone components.

    The components of Angular 13 and the previous versions depended on the ngModules. So, for example, if you want to include or use any additional module, pipes, services, or even directories in the component, you need to import all such things in the module file.

    But in Angular 14, the scenario is entirely different. How? Let’s see a simple example of creating an Angular 14 standalone component. First, we will create one component, “HomeComponent”, as a standalone by using the command.

    ng generate component HomeComponent — standalone

    Copy
    D:\angular-14-application>ng generate component HomeComponent --standalone
    CREATE src/app/home-component/home-component.component.html (29 bytes)
    CREATE src/app/home-component/home-component.component.spec.ts (644 bytes)
    CREATE src/app/home-component/home-component.component.ts (401 bytes)
    CREATE src/app/home-component/home-component.component.css (0 bytes)
    
    

    Inside the HomeComponent file, you’ll see “standalone: true”, which means that this is the standalone component in your application.

    Copy
    //home-component.component.ts
    import { Component, OnInit } from '@angular/core';
    import { CommonModule } from '@angular/common';
    
    @Component({
      selector: 'app-home-component',
      standalone: true,
      imports: [CommonModule],
      templateUrl: './home-component.component.html',
      styleUrls: ['./home-component.component.css']
    })
    export class HomeComponentComponent implements OnInit {
      constructor() { }
      ngOnInit(): void {
      }
    }
    
    

    So, you can easily import whatever stuff, like services, directories, and pipes, inside this component.

    Planning To Build A Robust SPA For Your Business?

    Albiorix is a top-rated Angular development company having a team of talented developers to provide the best optimum IT solutions.

    Let’s say you have 20 components in a single module. And in one component, you must import multiple services, directives, or whatever. So, it becomes mandatory for you to import all such services or directories inside the “app.module.ts” file, which applies to all the 20 components included in the application. Your application will load more, resulting in lower performance. Correct?

    But Angular 14 makes it easy for the developers to import specific services or directories within a particular component.   One drawback of this standalone component is that it does not have a stable API, and there are more chances of potential changes to it.

    Related Post: What is Promise in Angular

  2. Typed Angular Forms

    As we know, Angular typically consists of Template-Driven and Reactive Forms. So far, in Angular 13’s reactive forms. Let’s say you define a type of Reactive form and you want to update its value to another. It’s simple, but it’s not a good practice in Angular as it strictly uses TypeScript programming language.

    To make it easy for the developers, Angular 14 introduced Typed Angular Forms. It uses strictly Typing and strongly eliminates the implementation of strict typing for the Angular Reactive Forms Package.

    Angular 14’s Typed forms aim to ensure that the values inside form controls, groups, and arrays are type-safe across the API surface. It helps Angularjs developers to enable safer forms, especially for deeply nested complex cases.

    The excellent part of Angular 14 is that it allows the developers to use “UnTypedFormGroup” if they do not want to use Typed Forms.

  3. Streamlined Page Title Accessibility

    In Angular 13 and the previous version, it was challenging for the developers to change the title of different pages in the application. 

    Angular 14  allows the developers to add the title of every page by using the “title” property  as shown below.

    Copy
    const routes: Routes = [{
      path: 'home',
      component: HomeComponent
      title: 'My App - Home'  // <-- Page title
    }, {
      path: 'about',
      component: AboutComponent,
      title: 'My App - About Me'  // <-- Page title
    }];
    
  4. Extended Developer Diagnostics

    This feature of Angular 14 is really a boon for Angular developers. For example, if there is an error in any file except the template file, it will not throw any error. Sound astonishing?

    In the below code, we have added some text in the “ts” file, and we can see the error line.

    Copy
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent, abcdef
      ],
      imports: [
        BrowserModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    

    Likewise, in the template file, we are not getting any red lines:

    Copy
     :host {
    Font-family: -apple-system, BloinkMacSystemFont, "Segoe UI", Roboto, Helvetical, Arial, Sans-Serif
    Font-size: 14px;
    Color: #333;
    Box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale; abcdef
    }
    

    New extended diagnostics provide an extendable framework that gives you more error details in your templates and suggests how you can improve them. Diagnostics give compile-time warnings with precise, actionable suggestions for your templates, catching bugs before run-time.

  5. Banana in a box” Error

    Generally, Angular developers working in AngularJS development company typically use brackets and parenthesis in dealing with two-way data binding functionality. 

    You’ll get a syntax error by writing ([]) instead of [()]. As () looks like a banana and [] looks like a box, it is represented as “banana in a box”.

    While this error is technically valid syntax, our CLI can recognize that this is rarely what developers intend. Therefore, in the v13.2 release, we introduced detailed messaging on this mistake and guidance on how to solve this, all within the CLI and your code editor.

  6. Catch nullish coalescing on non-nullable values

    When the developers are working with Angular templates, extended diagnostics usually raise errors for (??) – nullish coalescing operators.

    This feature of Angular 14 arises when the specific input is “not nullable. In simple words, when its type is not defined or has not included null.

    Moreover,  in real-time,  the extended diagnostic features show warnings like ng build, ng serve, and in real-time with the Angular Language Service. tsconfig.json is the primary file where the developers can work with basic configurations and specify if diagnostics should be a warning, error, or suppressed.

  7. Angular CLI Enhancements

    With the launch of Angular 14, more consistency across the Angular CLI has been added to the developers by standardized CLI argument parsing. Moreover, the developers can include –lower-skewer-case format in every flag.

    With Angular 14, a feature has been initiated that has removed deprecated camel case arguments support and added support for combined aliases usage.

    1. ng completion

      Many times, it happens that the developers give the command “ng sevre” instead of “ng serve”. But, of course, it’s a typo, and it is not a big deal. And such typos mistakes throw an error in the command line prompt. 

      Considering the points from the Angular developer’s community, Angular 14 introduced a new ng completion that introduces real-time type-ahead autocompletion!

      To ensure all Angular developers know about this, the CLI will prompt you to opt-in to autocomplete during your first command execution in v14. You can also manually run ng completion; the CLI will automatically set this up for you.

    2. ng analytics

      The CLI’s analytics command allows you to control analytics settings and print analytics information. The more detailed output clearly communicates your analytics configurations and provides our team with telemetry data to inform our project prioritization. It sincerely helps a lot when you turn it on!

    3. ng cache

      ng cache provides a way to control and print cache information from the command line. You can enable, disable, or delete from disk, and print statistics and information.

    Related Post: Resolver in Angular

  8. Angular DevTools is Available Offline and in Firefox

    The Angular DevTools debugging extension now supports offline use, thanks to a community contribution by Keith Li. For Firefox users, find the extension in the Add-ons for Mozilla.

Looking For the Best Front-End Development Services?

Create seamless one-page web applications with reusable code components with our ReactJS development solutions.

How To Install Angular 14?

The first step is to install Angular 14 using npm. Just execute the following command in the CLI.

Copy
D: \> npm install - - global @angular/cli@next

How to Upgrade to Angular 14?

Read out the instructions on its official website to upgrade your Angular application to Angular v14 – https://update.angular.io/

Additional Summary

  • Along with this release, we have updated the public Angular 14 roadmap to reflect the status of current and future team projects and explorations.
  • TypeScript versions older than 4.6.0 are no longer supported.
  • Reactive form types such as FormControl and FormGroup now have generic type parameters and infer stricter types. A migration will convert existing usages to new Untyped-prefixed aliases which preserve the existing behavior.
  • Make sure you are using Node 14.15.0 or later.

Conclusion

As we’ve seen, Angular 14 is becoming more powerful for the developers as it includes features running from typed forms and Angular 14 standalone components to new primitives in the Angular CDK (component dev kit)

We’ve gone through the detailed information about every feature explained with examples to get information about the Angular 14 features. 

I hope this will help you with your upcoming/existing project using the latest Angular14 version.