Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Sunday, August 23, 2020

Angular Observable

Promises vs Observable

Promise is eager, once they are initialized they trigger the underlying actions and returns the result
Observable is lazy, they don’t trigger until it has a subscriber.

Promises returns only one value
Observable can return multiple values overtime to its subscribers

Promise cannot be canceled, once a promise action is triggered it will execute and return the result
Observable can be canceled, we can call unsubscribe to stop receiving responses from the observable

Promises can be converted to observables, the RxJs library provides a from operator which can convert a promise to an observable. We can use this to deal with some legacy code that is returning promises.

import { from } from 'rxjs';
const myObservable = from(myPromise)

Consuming Observables using async pipe

To consume an Observable using async pipe we need to use the | async syntax in the components view template. In the previous post, we saw how to consume an Observable (response from a http API call) by subscribing to the Observable.

The view template consumes this Observable and displays the response from the http call in the View template. The async pipe automatically subscribes and unsubscribes to the Observable, whenever a new value is emitted from the Observer the async pipe automatically detects the change and refreshes the component.

Consuming Observable using Subscribe

To consume an observable by subscribing, we need to call the subscribe() method and capture the result/error objects returned by the observable. In this sample, we will get a list of users using a http.get call which returns an observable.

Creating observable using Inline Arrow functions

In the previous post we created a separate function and passed it as a parameter to create an Observable. In this post we shall see on how to create an Observable using an inline arrow function.
In the below example we will create an Observable with an inline function which emits the current time, we use setInterval to emit a new value every 1 second.

Creating Observable

We can create our own Observable by creating a function that takes an observer parameter. The function will be passed to create the Observable. When someone subscribes to the observable, the function is called and returns the values emitted from the function.

In the below sample we create a function listGenerator, which takes an observer as a parameter and emit list values one at a time using .next().

Friday, August 21, 2020

What is Async Pipe?

Async Pipe is an impure pipe which helps to make it easier to work with Observables. The Async Pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

For promises, it automatically calls the "then" method.
For observables, it automatically calls subscribe and unsubscribe.

To use the Async Pipe to handle observables in Angular template we use | async followed by the observable, this will automatically subscribe to the observable and refreshes the component whenever a new value is emitted from the observable.

AsyncPipe uses the OnPush change detection out of the box. We need to make sure that all our business logic is immutable and always returns new objects.

Observable in Angular

Angular internally uses Observables for different features, which needs to listen to specific sources and trigger actions based on specific events/values. Angular uses Observables for the following.

What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. RxJS provides an implementation of the Observable type.

RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on.

What is an Observable?

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of state changes.  Observables get their name from the Observer design pattern. The Observable sends notifications while the Observer receives them.

Saturday, August 15, 2020

Angular Services

Angular Dependency Injection

Dependency Injection (DI) is a pattern in which a class gets its dependent classes from an external source/framework instead of instantiating them within the class.  Dependency Injection makes an application easy to maintain and makes testing easier, since the dependent objects are injected from outside we can use Mock objects to test the behavior of a class when the actual object is not ready for testing.

Angular Singleton Services

A Singleton Service is one which has only one instance shared across the entire Angular App, it is a great way to share data across different components even if they don’t have any Hierarchal relationship. Services can be declared Singleton by setting the providedIn property of the @Injectable() to "root", when creating the service.

@Injectable({
  providedIn: 'root',
})

Thursday, August 13, 2020

Angular Provider Scope

In the previous post, we saw on how to make a service available globally by declaring the @Injectable providedIn: 'root'. We can also declare module-level services using ProvidedIn, in this post we shall see on how to declare module-level service using @Injectable

To limit the scope of a service to a module we need to specify the module in the providedIn instead of ‘root’. In the below code the HellpService is made available only to the HelloModule, the service is not available to any other Modules in the Application.

Angular Service Scope

In Angular, Services are a great way to share information among Components that don't know each other. Based on how we register a service we can control the scope/visibility of the service across the Application.

Services can be registered with 3 levels of scope
1. Global Scope
2. Module Scope
3. Component Scope

Wednesday, August 12, 2020

What are Angular Services?

 In Angular, a Service is a class that is used to provide shared features across different components. Components are the View layer they deal only with UI specific features. Functional tasks like ajax calls, business logic, validations, logging, etc are delegated to the services.

Services are a great way to share information among Components that don't know each other. Based on how we register a service we can control the scope / visibility of the service across the Application. Services can be registered with 3 levels of scope

1. Global Scope
2. Module Scope
3. Component Scope

Wednesday, December 5, 2018

What are Angular Elements

Angular Elements is an interesting new feature introduced in Angular 6. Angular Elements allows us to create Angular Components, package them and allows us to re-use the components in non-Angular environments like jQuery, HTML etc.

Angular Elements are angular components which are packaged into Custom Elements. Custom Elements allows us to create custom HTML tags which have their pre-defined functionality, these custom tags can be used in any HTML page. Custom Elements is a Web Component feature which helps us create custom elements and reuse them in HTML pages.

Saturday, December 1, 2018

Angular Custom Pipes example

Angular provides built-in pipes like date, uppercase, etc to format/transform values. Angular also allows us to create custom pipes for situations where we cannot use the built-in pipes. Custom pipes are created using the @Pipe decorator. Pipes are classes which implement PipeTransform and use the transform() method to provide the transformation logic. The trasform() method takes the input value and pipe parameter values as its arguments.

We can use the ng generate pipe command to create custom pipes. In the following example we will create a simple squareNumber pipe which will take the input value and return the square value of the number. Let us start by create a new custom pipe using the following command.