Angular 2 AsyncPipe Example

The async | pipe subscribes to a Promise or an Observable.

The async returns the latest value emitted. When a new value is emitted the Component is flagged with “To be checked changes”.

angular 2 asyncpipe example
angular 2 asyncpipe example

 

If it’s your first time with Angular 2, Please check our hello world (step by step + npm and environment setup) tutorial here. To be able to run this example.

 

Step 1

We create our component: angular-2-asyncpipe-example.ts

 

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';

@Component({
    selector: 'angular-2-async',
    template: `<div>
                 <h2>Angular 2 AsyncPipe Example – Typescript</h2>
                 <p class="bg-primary">When you click the button below, a car name will be shown right here :
                 <span class="badge">{{ carBMName | async }}</span>
                 </p>
                 <button class="btn btn-success" (click)="clickedToResolve()">{{ responseArrived ? 'Previous State' : 'Resolve the Promise' }}</button>
                </div>`
})
export class Angular2AsyncPipeExample {
    carBMName: Promise<string> = null; // declare a Promise

    responseArrived: boolean = false; // we store the state of the response (arrived or not)

    private resolve: Function = null; // once the Promise is resolved we call the suscces method

    constructor() { this.prevState(); }

    prevState() {
        this.responseArrived = false;
        this.carBMName = new Promise<string>((resolve, reject) => { this.resolve = resolve; });
    }

    clickedToResolve() {
        if (this.responseArrived) { // if we have already the response , go back to the previous State
            this.prevState();
        } else { // put a response [e.g. 'BMW Serie 1 : )' ]
            this.resolve("BMW Serie 1 : )");
            this.responseArrived = true; // now responseArrived is true.
        }
    }
}
  • We create a Promise with the name of carBMName. (We bind this Promise to the View).
  • We declare a flag (Boolean) variable to track the response state (responseArrived ).
  • Resolve, this function is used as a first parameter of our Promise. Once the Promise is resolved we call the success method (to return the Data).
  • Constructor calls the prevState for the initialization.

 

Explanation if you are new to Promises:

Promise class in Angular 2: its constructor needs a function with 2 parameters (resolve, reject)

If(ok) {

resolve(data); // success

} else {

reject(‘none’) //failure

}

Step 2

We create the main component: angular-2-asyncpipe-app.component.ts

 

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';
import {Angular2AsyncPipeExample} from "./angular-2-asyncpipe-example";


@Component({
    selector: 'my-app',
    template: `
                <angular-2-async>loading...</angular-2-async>
               `,
    directives: [Angular2AsyncPipeExample]
})
export class Angular2AsyncPipeExampleAppComponent {

}

Step 3

We bootstrap our application: main.ts

 

import {bootstrap} from 'angular2/platform/browser';
import {Angular2AsyncPipeExampleAppComponent} from "./core/angular2common/AsyncPipe/angular-2-asyncpipe-app.component";

bootstrap(Angular2AsyncPipeExampleAppComponent);

Step 4

The root app: index.html

 

<html>
<head>
    <title>Angular Typescript from angulartypescript.com</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 0. Css -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/router.dev.js"></script>
    <script src="node_modules/angular2/bundles/http.dev.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('app/main')
                .then(null, console.error.bind(console));
    </script>

    <link rel="stylesheet" href="src/css/app.css">
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>

Done!