Wednesday, August 26, 2020

What's new in Angular 10

Angular 10 was released on June 24, 2020. Angular 10 offers support for TypeScript v3.9

To upgrade an existing Angular 9 application to Angular 10, just run the ng update command as follows

What's new in Angular 9

Angular 9 was released on February 6, 2020. Ivy compiler and runtime are now made default in Version 9, this helps in faster build and smaller bundle size. Angular 9 has been updated to work with TypeScript 3.6 and 3.7
To upgrade an existing Angular 8 application to Angular 9, just run the ng update command as follows

ng update @angular/cli @angular/core

One of the major features of Angular 9 is making the Ivy compiler as default, this offers the following improvements

What's new in Angular 8

Angular 8 was released on May 28, 2019. Angular 8 provides features like Differential loading, Dynamic imports for lazy routes, Web workers, TypeScript 3.4 support and Angular Ivy & Bazel as an opt-in preview features.

Differential loading
With differential loading, the Angular production build will produce 2 separate bundle files. One ES5 bundle for legacy browsers. Another ES6 bundle for the latest browsers which support ES6 features. This helps in improving the loading speed and performance in modern browsers since this bundle file is smaller in size.

Tuesday, August 25, 2020

Angular Elements

Angular EventEmitter

Using EventEmitter with @Output

In the previous post, we saw what EventEmitters are and how they are used in combination with @Output decorator to handle communicate from Child component to the Parent component. In this post, we shall see a full example of how this is implemented.

In the example, we have a ParentComponent and a ChildComponent, the child component has a button and a @Output decorator. In the buttons click event, we will trigger the emit event of the EventEmitter associated with the @Output parameter, we will also send a payload along with the emit.

What are EventEmitters?

Angular applications are made using Components, most often we will have to arrange the components in a hierarchy (parent/child components). We will have to pass values from the parent to child components and from the child to parent component to make the App functional.

To pass values from a parent component to a child component we use the @Input property/decorator.
To pass values from a child component to a parent component we need to emit an event using @Output and EventEmitter. Both are parts of the @angular/core.

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',
})

Friday, August 14, 2020

Redux Overview

Redux Thunk Overview

Fetch async data using Redux Thunk example

In the previous post we saw about setting up Redux Thunk for a React Redux application, in this post we shall see an example for fetching async data from an API call using axios and redux thunk, and update the store with the response from the API call.

Assuming that we have the required npm packages installed and the redux-thunk middleware configuration is setup as specified in the previous post we will go ahead with the actual implementation of redux-thunk and axios api calls.

We create 2 actions, first to set the locations array in the store and the 2nd to set a success/failure message.

Adding Redux Thunk Middleware to a React-Redux App

In the previous post we saw about Redux Thunk middleware and its need, in this post we shall see on how to setup the redux-thunk middleware in a React Redux application. Assuming that we have a working React Redux application we shall see on how to add redux-thunk middleware to it.

To start with we need to install the redux-thunk middleware npm package.

npm install --save redux-thunk

Next we need to add the middleware in the createStore method as follows.

What is Redux Thunk

Redux Thunk is a middleware that lets us perform asynchronous operations like API/Ajax calls before modifying the data in a store. Middleware provides a way to interact with actions that have been dispatched to the store before they reach the store's reducer. Examples of different uses for middleware include logging actions, reporting errors, making asynchronous requests, and dispatching new actions.

Adding Redux to a React App

In the previous few posts we saw about Action, Reducer and Store concepts about Redux. In this post we shall see on how to put all of these together to add a Redux store to a React application.

In this sample we will create a simple React application, with a textbox where the user can type his name and a button on click of which a Welcome message is displayed with the name. The onChange event of the textbox and the onClick event of the button will dispatch actions to update the corresponding property in redux store.

mapDispatchToProps in Redux

mapDispatchToProps function is used to dispatch actions to the store in a react-redux application.
To dispatch an action to the store we need to call store.dispatch. In a React Redux application the React component does not have access to the store directly hence it cannot call store.dispatch. The connect method which connects react and redux provides the mapDispatchToProps through which react components can dispatch actions.

If mapDispatchToProps is not defined in connect, there is another way to dispatch actions from React components. In this case props.dispatch is passed to the component and using this we can dispatch actions to the store.

mapStateToProps in Redux

The is a function which takes the state as an input parameter and maps the properties in the state to props mapStateToProps  in the component.

mapStateToProps take the state object (the same value returned by a call to store.getState()) as the first argument and return a plain object containing the data that the connected component needs.  This function should be passed as the first argument to connect, and will be called every time when the Redux store state changes.

store in Redux

In Redux store is the state object which holds the Application state. The current state can be accessed using store.getState() and any changes to the state can be performed by dispatching an action to the reducer.

In the previous posts, we saw how to create the store object using createStore and use it to initialize the application. Redux store also allows us to subscribe to events that update the store object. This can be useful to debug changes to the redux store.

In the createStore code of the previous example we will add a subscription to display changes to the state to the console as follows.

combineReducers in Redux

In the previous post, we saw about Redux reducers, how to create them, and bind it to the store when the Application gets initialized. This approach of creating and initializing a single reducer works well for small Applications.

When the application grows it might be difficult to hold the state of all the components in a single file, as it will grow too big making it difficult to maintain, we would like to split the reducer code across different reducer files for maintainability. To achieve this redux provides a utility combineReducers(), this can take multiple reducers and merge them into a single reducer before assigning it to the store.

Let us extend the previous example, add multiple reducers and use combineReducers() to merge them into a single reducer and assign it to the state as follows.

Reducers in Redux

Reducers are pure functions in redux which are used to modify the state object of the Application. All Actions are handled in reducers they will get the payload from the action and modify the state as defined.

Reducers take the previous state of the app and return a new state based on the action passed to it.
As pure functions, they do not change the data in the object passed to them or perform any side effect in the application. Given the same object, they should always produce the same result. Actions performed on the state always return a new state. Thus, the state is very easy and predictable.

In the previous post, we was a SET_NAME action below is the reducer which handles the SET_NAME action.

Actions in Redux

An Action is a plain JavaScript object which has a Type property which defined the type of the actions and an optional payload. Actions are triggers which are used to send information from the application to the store and these are the only way in which the redux store can be modified.

Below is an example of a simple action object.

What is Redux?

Redux is a predictable state container for JavaScript applications.

For React applications Redux provides a centralized state container for the whole Application. Redux holds a large JavaScript state object which can be shared across the application.

Thursday, August 13, 2020

React TypeScript Examples

React TypeScript stateless Function component example

In the previous post, we saw on how to create a React component with state and event handlers using TypeScript. We can also create simple function components using TypeScript which does not require a state. Usually, these types of components are used for UI components. Class components with the state are used for container components and Function components are used for UI only components which do not interact with the state containers.

In this post, we will see how to create a simple Hello World function component in React using TypeScript.

React TypeScript Parent - Child components example

In the previous post we saw a React class component written in TypeScript, the component had state support and event handling (button click event and text change event). The component has a textbox and a button, we handle the onChange event of the textbox set the value in the name state property. We capture the onClick event of the button and set a greeting text in the message state object, this message is displayed in the screen

In this post we will alter this component a bit so that the greeting message is passed as a property from the parent component.

React TypeScript component with State and Events

In the previous post we saw on how to do a simple Hello World application in React with TypeScript using the create-react-app package. In this post we will move on the next step we will add state support and event handling (button click event and text change event) to the component.

The React component initializes state, notice that we are using the State interface with strongly types properties to define the state object, this is the advantage of TypeScript it allows us to define strongly typed properties which help us capture type errors during development. The state object has 2 properties message and name.

React ref overview

React Component Lifecycle methods examples

React Component Lifecycle Overview

React ES6 Examples

React 16.3 Context, Ref & Lifecycle changes

React 16 Fragments, Portals & Error boundaries

React Overview

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