1567237350
There’s going to be nothing quite like this available on the web, as we will be promoting best practices, revealing hidden tips and tricks, and getting a real grasp on how and when these hooks are called.
Before we dive into the first installment of the series, let’s review briefly all of the available lifecycle hooks and where they can be used.
Available Lifecycle Hooks:
Lifecycle Hooks Can Be Used On:
Here is a component with all eight (8) hooks implemented:
import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, OnChanges, OnDestroy, OnInit } from '@angular/core';@Component({
selector: ‘app-home’,
templateUrl: ‘./home.component.html’
})
export class HomeComponent
implements
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
ngOnChanges() {}ngOnInit() {}
ngDoCheck() {}
ngAfterContentInit() {}
ngAfterContentChecked() {}
ngAfterViewInit() {}
ngAfterViewChecked() {}
ngOnDestroy() {}
}
If you’re like me, you had a few questions after reading the docs. Clean up what? Avoid memory leaks? Hey—that’s not very specific, it sounds like we need to uncover this a bit more. So here we go!
In this article, we will review how to implement OnDestroy
, common use cases for OnDestroy
, and wrap-up with a bonus enhancement to OnDestroy
that will allow it to be executed with browser events.
OnDestroy
is an Angular lifecycle method, that can hooked into on components
and directives
in Angular. By defining a specific method named ngOnDestroy
on our class, we are telling the Angular runtime, that it should call our method at the appropriate time. This is a powerful and declarative way to add specific cleanup logic to the end of our class lifecycle.
As with other Angular lifecycle methods, adding the actual hook for OnDestroy
is relatively simple.
The first step to implementing OnDestroy
is to add OnDestroy
after the implements
keyword on a component
or directive
.
Here’s a typical component without any lifecycle hooks:
import { Component } from ‘@angular/core’;@Component({…})
export class MyValueComponent {}
Our first change is to import OnDestroy
from Angular’s core and then create a contract with implements OnDestroy
:
Fun Fact Time: Technically it’s not required to implement the interface, Angular will call ngOnDestroy
regardless, however, it’s very helpful for type-checking, and to allow other developers to quickly identify which lifecycle hooks are in use on this class.
import { Component, OnDestroy } from ‘@angular/core’;@Component({…})
export class MyValueComponent implements OnDestroy {}
Now that we have added the OnDestroy
after implements
the TypeScript intellisense will underline the class declaration in red, giving a warning that ngOnDestroy
was not found. Let’s fix that by creating our new ngOnDestroy
method.
Example Component Before:
import { Component, OnDestroy } from ‘@angular/core’;@Component({…})
export class MyValueComponent implements OnDestroy {}
Example Component After:
import { Component, OnDestroy } from ‘@angular/core’;@Component({…})
export class MyValueComponent implements OnDestroy {
ngOnDestroy() {
// cleanup logic goes here
}
}
You’ll also note that this lifecycle hook takes no arguments, unlike some of the others we’ll be covering in later articles.
As you can see, implementing OnDestroy
is fairly straightforward. Now, let’s explore some common use cases for OnDestroy
. At the beginning of the article, we mentioned that Angular recommends the following: “Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called just before Angular destroys the directive/component.” Let’s explore this further.
We want to avoid memory leaks, but what are they? According to Google’s definition, a memory leak is “a failure in a program to release discarded memory, causing impaired performance or failure.” Memory leaks are typically created from not understanding how things work and wreak havoc on app performance. Let’s explore an example of one such memory leak – so you’re primed to tackle your OnDestroy logic in future!
Let’s imagine a scenario wherein we have a component that has one button. When we click the button a call is made to a method on a AuthService
that returns an Observable
containing the name of the logged in user. The button click event subscribes to this Observable
and displays a window alert with the username.
Here’s how the component might look before implementing OnDestroy
:
show-user.component.ts
import { Component } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;@Component({…})
export class ShowUserComponent {
constructor(private authService: AuthService) {}showLoggedInUser() {
this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}
}
show-user.component.html
<button (click)=“showLoggedInUser()”>Show Logged In User</button>
At first glance, you might say, “This component looks great, it subscribes to the service and shows an alert on click”. You’d be correct, but what do you think would happen if this ShowUserComponent
was used in the AppComponent
and displayed with an *ngIf
conditionally. Perhaps a scenario exists where the ShowUserComponent
is destroyed and then displayed again.
Well, I can tell you what would happen, some really odd, strange behavior. If the component was instantiated, the user clicked the button and alert displayed, then one subscription would be created. Then let’s say, the component was re-created and the user clicked the button again, how times would the alert display? Two times, at least! This is because a second subscription would be created and then fired when the button is clicked.
This is creating the “memory leak” and could quickly get out of hand, with our alert being shown exponentially (just imagine the impact across an entire codebase without cleaning things up properly!). Let’s read on to learn how to plug this memory leak using OnDestroy
.
To fix the memory leak we need to augment the component class with an implementation of OnDestroy
and unsubscribe
from the subscription. Let’s update our component adding the following:
OnDestroy
to the typescript import
OnDestroy
to the implements
listmyUserSub: Subscription
to track our subscriptionthis.myUserSub
equal to the value of this.authService.getLoggedInUserName().subscription
ngOnDestroy
this.myUserSub.unsubscribe()
within ngOnDestroy
if a subscription has been set.Best Practice: Notice that we are checking ifthis.myUserSub
is “truthy” before attempting to callunsubscribe
. This avoids a potential situation wherein the subscription may have never been created, thus preventing a ghastlyunsubscribe is not a function
error message.
The updated component will look something like this:
import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { Subscription } from ‘rxjs’;@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
}
}
Now we can ensure that our alert will only ever be displayed once per button click.
Great! Now we have some background on ngOnDestroy
and how cleaning up memory leaks is the primary use case for this lifecycle method.
Exploring further, we find more examples of use cases for ngOnDestroy
including making server-side cleanup calls, and preventing user navigation away from our component. Let’s explore these additional scenarios, and how we can enhance ngOnDestroy
to meet our needs.
As with other lifecycle methods in Angular, we can modify ngOnDestroy
with async
. This will allow us to make calls to methods returning a Promise
. This can be a powerful way to manage cleanup activities in our application. As we read on we will explore an example of this.
Let’s pretend that we need to perform a server-side user logout when ShowUserComponent
is destroyed. To do so we would update the method as follows:
async
in front of the method name ngOnDestroy
AuthService
to logout
using the await
keyword.Our updated ShowUserComponent
will look something like this:
import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}
Tada! Now when the component is destroyed an async
call will be made to logout the user and destroy their session on the server.
As an alternative to manually calling unsubscribe
you could take things a step further and make use of the takeUntil
RxJS operator to “short-circuit” the subscription when a value is emitted.
Confused? Well imagine this…
destroyed$
. This property will be a ReplaySubject<boolean> = new ReplaySubject(1)
, meaning it only ever emits one boolean value..pipe
to the this.authService.getLoggedInUserName()
subscriptiontakeUntil(this.destroyed$)
into the pipe
methodngOnDestroy
method to push a new value to the destroyed$
subject, using this.destroyed$.next(true)
ngOnDestroy
method to call complete
on the destroyed$
subject.The finished component will look something like this:
import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { ReplaySubject } from ‘rxjs’;
import { takeUntil } from ‘rxjs/operators’;@Component({…})
export class ShowUserComponent implements OnDestroy {
private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.pipe(takeUntil(this.destroyed$))
.subscribe(username => window.alert(You are logged in as ${username}!
));
}async ngOnDestroy() {
this.destroyed$.next(true);
this.destroyed$.complete();
await this.authService.logout();
}
}
With this new method in place, we no longer need to keep track of each subscription, check for truthy and call unsubscribe. The real power of this comes into play, when we have multiple subscriptions that need to be unsubscribed from. At that point, we would just add the takeUntil
to each subscription, and then leave our updated ngOnDestroy
to emit the destroyed$
true value to all the subscriptions.
Many developers are surprised to learn that ngOnDestroy
is only fired when the class which it has been implemented on is destroyed within the context of a running browser session.
In other words, ngOnDestroy
is not reliably called in the following scenarios:
This could be a deal-breaker when thinking about the prior example of logging the user out on destroy. Why? Well, most users would simply close the browser session or navigate to another site. So how do we make sure to capture or hook into that activity if ngOnDestroy
doesn’t work in those scenarios?
TypeScript decorators are used throughout Angular applications. More information can be found here in the official TypeScript docs.
To ensure that our ngOnDestroy
is executed in the above mentioned browser events, we can add one simple line of code to the top of ngOnDestroy
. Let’s continue with our previous example of ShowUserComponent
and decorate ngOnDestroy
:
HostListener
to the imports
@HostListener(‘window:beforeunload’)
on top of ngOnDestroy
Our updated ShowUserComponent
will look something like this:
import { Component, OnDestroy, HostListener } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}@HostListener(‘window:beforeunload’)
async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}
Now our ngOnDestroy
method is called both when the component is destroyed by Angular AND when the browser event window:beforeunload
is fired. This is a powerful combination!
@HostListener()
is an Angular decorator that can be placed on top of any class method. This decorator takes two arguments: eventName
and optionally args
. In the above example, we are passing window:beforeunload
as the DOM event. This means that Angular will automatically call our method when the DOM event window:beforeunload
is fired. For more information on @HostListener
check out the official docs.
If we want to use this to prevent navigation away from a page or component then:
$event
to the @HostListener
argumentsevent.preventDefault()
event.returnValue
to a string value of the message we would like the browser to displayAn example would look something like this:
@HostListener(‘window:beforeunload’, [‘$event’])
async ngOnDestroy($event) {
if (this.myValueSub) {
this.myValueSub.unsubscribe();
}await this.authService.logout();
$event.preventDefault();
$event.returnValue = ‘Are you sure you wanna close the page yo?.’;
}
PLEASE NOTE: This is not officially supported by Angular!OnDestroy
andngOnDestroy
suggest that there is no input argument onngOnDestroy
allowed. While unsupported, it does in fact still function as normal.
window:beforeunload
is an event fired right before the window
is unloaded. More details can be found in the MDN docs.
A couple points to be aware of:
event.returnValue
to a string of the message you would like to display. More details in this example.That brings us to the end of the article, hopefully you have been able to glean some good advice on why and how to use OnDestroy
logic in your applications.
Thanks for reading. If you liked this post, share it with all of your programming buddies!
Originally published on ultimatecourses.com
#angular #angular-js #javascript #typescript #web-development
1598940617
Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.
In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!
For Installing Angular on your Machine, there are 2 prerequisites:
First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js
Download and Install Node.js version suitable for your machine’s operating system.
Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
1593184320
What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.
Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.
We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.
Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
bootstrap: [AppComponent]
})
Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:
#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular
1567237350
There’s going to be nothing quite like this available on the web, as we will be promoting best practices, revealing hidden tips and tricks, and getting a real grasp on how and when these hooks are called.
Before we dive into the first installment of the series, let’s review briefly all of the available lifecycle hooks and where they can be used.
Available Lifecycle Hooks:
Lifecycle Hooks Can Be Used On:
Here is a component with all eight (8) hooks implemented:
import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, OnChanges, OnDestroy, OnInit } from '@angular/core';@Component({
selector: ‘app-home’,
templateUrl: ‘./home.component.html’
})
export class HomeComponent
implements
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
ngOnChanges() {}ngOnInit() {}
ngDoCheck() {}
ngAfterContentInit() {}
ngAfterContentChecked() {}
ngAfterViewInit() {}
ngAfterViewChecked() {}
ngOnDestroy() {}
}
If you’re like me, you had a few questions after reading the docs. Clean up what? Avoid memory leaks? Hey—that’s not very specific, it sounds like we need to uncover this a bit more. So here we go!
In this article, we will review how to implement OnDestroy
, common use cases for OnDestroy
, and wrap-up with a bonus enhancement to OnDestroy
that will allow it to be executed with browser events.
OnDestroy
is an Angular lifecycle method, that can hooked into on components
and directives
in Angular. By defining a specific method named ngOnDestroy
on our class, we are telling the Angular runtime, that it should call our method at the appropriate time. This is a powerful and declarative way to add specific cleanup logic to the end of our class lifecycle.
As with other Angular lifecycle methods, adding the actual hook for OnDestroy
is relatively simple.
The first step to implementing OnDestroy
is to add OnDestroy
after the implements
keyword on a component
or directive
.
Here’s a typical component without any lifecycle hooks:
import { Component } from ‘@angular/core’;@Component({…})
export class MyValueComponent {}
Our first change is to import OnDestroy
from Angular’s core and then create a contract with implements OnDestroy
:
Fun Fact Time: Technically it’s not required to implement the interface, Angular will call ngOnDestroy
regardless, however, it’s very helpful for type-checking, and to allow other developers to quickly identify which lifecycle hooks are in use on this class.
import { Component, OnDestroy } from ‘@angular/core’;@Component({…})
export class MyValueComponent implements OnDestroy {}
Now that we have added the OnDestroy
after implements
the TypeScript intellisense will underline the class declaration in red, giving a warning that ngOnDestroy
was not found. Let’s fix that by creating our new ngOnDestroy
method.
Example Component Before:
import { Component, OnDestroy } from ‘@angular/core’;@Component({…})
export class MyValueComponent implements OnDestroy {}
Example Component After:
import { Component, OnDestroy } from ‘@angular/core’;@Component({…})
export class MyValueComponent implements OnDestroy {
ngOnDestroy() {
// cleanup logic goes here
}
}
You’ll also note that this lifecycle hook takes no arguments, unlike some of the others we’ll be covering in later articles.
As you can see, implementing OnDestroy
is fairly straightforward. Now, let’s explore some common use cases for OnDestroy
. At the beginning of the article, we mentioned that Angular recommends the following: “Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called just before Angular destroys the directive/component.” Let’s explore this further.
We want to avoid memory leaks, but what are they? According to Google’s definition, a memory leak is “a failure in a program to release discarded memory, causing impaired performance or failure.” Memory leaks are typically created from not understanding how things work and wreak havoc on app performance. Let’s explore an example of one such memory leak – so you’re primed to tackle your OnDestroy logic in future!
Let’s imagine a scenario wherein we have a component that has one button. When we click the button a call is made to a method on a AuthService
that returns an Observable
containing the name of the logged in user. The button click event subscribes to this Observable
and displays a window alert with the username.
Here’s how the component might look before implementing OnDestroy
:
show-user.component.ts
import { Component } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;@Component({…})
export class ShowUserComponent {
constructor(private authService: AuthService) {}showLoggedInUser() {
this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}
}
show-user.component.html
<button (click)=“showLoggedInUser()”>Show Logged In User</button>
At first glance, you might say, “This component looks great, it subscribes to the service and shows an alert on click”. You’d be correct, but what do you think would happen if this ShowUserComponent
was used in the AppComponent
and displayed with an *ngIf
conditionally. Perhaps a scenario exists where the ShowUserComponent
is destroyed and then displayed again.
Well, I can tell you what would happen, some really odd, strange behavior. If the component was instantiated, the user clicked the button and alert displayed, then one subscription would be created. Then let’s say, the component was re-created and the user clicked the button again, how times would the alert display? Two times, at least! This is because a second subscription would be created and then fired when the button is clicked.
This is creating the “memory leak” and could quickly get out of hand, with our alert being shown exponentially (just imagine the impact across an entire codebase without cleaning things up properly!). Let’s read on to learn how to plug this memory leak using OnDestroy
.
To fix the memory leak we need to augment the component class with an implementation of OnDestroy
and unsubscribe
from the subscription. Let’s update our component adding the following:
OnDestroy
to the typescript import
OnDestroy
to the implements
listmyUserSub: Subscription
to track our subscriptionthis.myUserSub
equal to the value of this.authService.getLoggedInUserName().subscription
ngOnDestroy
this.myUserSub.unsubscribe()
within ngOnDestroy
if a subscription has been set.Best Practice: Notice that we are checking ifthis.myUserSub
is “truthy” before attempting to callunsubscribe
. This avoids a potential situation wherein the subscription may have never been created, thus preventing a ghastlyunsubscribe is not a function
error message.
The updated component will look something like this:
import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { Subscription } from ‘rxjs’;@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
}
}
Now we can ensure that our alert will only ever be displayed once per button click.
Great! Now we have some background on ngOnDestroy
and how cleaning up memory leaks is the primary use case for this lifecycle method.
Exploring further, we find more examples of use cases for ngOnDestroy
including making server-side cleanup calls, and preventing user navigation away from our component. Let’s explore these additional scenarios, and how we can enhance ngOnDestroy
to meet our needs.
As with other lifecycle methods in Angular, we can modify ngOnDestroy
with async
. This will allow us to make calls to methods returning a Promise
. This can be a powerful way to manage cleanup activities in our application. As we read on we will explore an example of this.
Let’s pretend that we need to perform a server-side user logout when ShowUserComponent
is destroyed. To do so we would update the method as follows:
async
in front of the method name ngOnDestroy
AuthService
to logout
using the await
keyword.Our updated ShowUserComponent
will look something like this:
import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}
Tada! Now when the component is destroyed an async
call will be made to logout the user and destroy their session on the server.
As an alternative to manually calling unsubscribe
you could take things a step further and make use of the takeUntil
RxJS operator to “short-circuit” the subscription when a value is emitted.
Confused? Well imagine this…
destroyed$
. This property will be a ReplaySubject<boolean> = new ReplaySubject(1)
, meaning it only ever emits one boolean value..pipe
to the this.authService.getLoggedInUserName()
subscriptiontakeUntil(this.destroyed$)
into the pipe
methodngOnDestroy
method to push a new value to the destroyed$
subject, using this.destroyed$.next(true)
ngOnDestroy
method to call complete
on the destroyed$
subject.The finished component will look something like this:
import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { ReplaySubject } from ‘rxjs’;
import { takeUntil } from ‘rxjs/operators’;@Component({…})
export class ShowUserComponent implements OnDestroy {
private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.pipe(takeUntil(this.destroyed$))
.subscribe(username => window.alert(You are logged in as ${username}!
));
}async ngOnDestroy() {
this.destroyed$.next(true);
this.destroyed$.complete();
await this.authService.logout();
}
}
With this new method in place, we no longer need to keep track of each subscription, check for truthy and call unsubscribe. The real power of this comes into play, when we have multiple subscriptions that need to be unsubscribed from. At that point, we would just add the takeUntil
to each subscription, and then leave our updated ngOnDestroy
to emit the destroyed$
true value to all the subscriptions.
Many developers are surprised to learn that ngOnDestroy
is only fired when the class which it has been implemented on is destroyed within the context of a running browser session.
In other words, ngOnDestroy
is not reliably called in the following scenarios:
This could be a deal-breaker when thinking about the prior example of logging the user out on destroy. Why? Well, most users would simply close the browser session or navigate to another site. So how do we make sure to capture or hook into that activity if ngOnDestroy
doesn’t work in those scenarios?
TypeScript decorators are used throughout Angular applications. More information can be found here in the official TypeScript docs.
To ensure that our ngOnDestroy
is executed in the above mentioned browser events, we can add one simple line of code to the top of ngOnDestroy
. Let’s continue with our previous example of ShowUserComponent
and decorate ngOnDestroy
:
HostListener
to the imports
@HostListener(‘window:beforeunload’)
on top of ngOnDestroy
Our updated ShowUserComponent
will look something like this:
import { Component, OnDestroy, HostListener } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!
));
}@HostListener(‘window:beforeunload’)
async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}
Now our ngOnDestroy
method is called both when the component is destroyed by Angular AND when the browser event window:beforeunload
is fired. This is a powerful combination!
@HostListener()
is an Angular decorator that can be placed on top of any class method. This decorator takes two arguments: eventName
and optionally args
. In the above example, we are passing window:beforeunload
as the DOM event. This means that Angular will automatically call our method when the DOM event window:beforeunload
is fired. For more information on @HostListener
check out the official docs.
If we want to use this to prevent navigation away from a page or component then:
$event
to the @HostListener
argumentsevent.preventDefault()
event.returnValue
to a string value of the message we would like the browser to displayAn example would look something like this:
@HostListener(‘window:beforeunload’, [‘$event’])
async ngOnDestroy($event) {
if (this.myValueSub) {
this.myValueSub.unsubscribe();
}await this.authService.logout();
$event.preventDefault();
$event.returnValue = ‘Are you sure you wanna close the page yo?.’;
}
PLEASE NOTE: This is not officially supported by Angular!OnDestroy
andngOnDestroy
suggest that there is no input argument onngOnDestroy
allowed. While unsupported, it does in fact still function as normal.
window:beforeunload
is an event fired right before the window
is unloaded. More details can be found in the MDN docs.
A couple points to be aware of:
event.returnValue
to a string of the message you would like to display. More details in this example.That brings us to the end of the article, hopefully you have been able to glean some good advice on why and how to use OnDestroy
logic in your applications.
Thanks for reading. If you liked this post, share it with all of your programming buddies!
Originally published on ultimatecourses.com
#angular #angular-js #javascript #typescript #web-development
1624138795
Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.
Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects
Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w
#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial
1625232772
Although Angular JS has bought headlines over the domain of Web application development, its relevance downtime does not offer any guarantee. Since the JavaScript application is the child of Google, its web features may have some value. Angular JS enables the developer to write most of the code in HTML which brings the application together. Such potentiality and simplicity of the program from the Angular Development Company made Angular popular among JavaScripts.
But the real question arises on the integrity and the safety Angular can provide to the industry. Angular regularly updates its libraries to fix security issues over earlier versions. However, the private and customized Angular versions fall back from the latest versions. These versions might lack the crucial security patches. As a piece of advice, developers can share their improvement requests in the community.
Backward compatibility indicates that the updated versions can function with the outdated versions. Hence, it can simplify the migration procedures to the latest Angular version. Some portions of the AngularJS apps need lazy loading to ease the update and to facilitate the transfer of large projects.
Since AngularJS tends to spoil backward compatibility, it might cause future problems in a program.
The Changing Face of Frameworks
There were several ups and downs in the Web application market over the past. A few years ago, SproutCore ruled the throne as a top framework. However, according to Google search trends, BackboneJS later stole the spotlight which again passed over to EmberJS. But, there remains no comparison for AngularJS.
Birthed by Adam Abrons and Misko Hevery, the Brat Tech engineers in 2009, the Angular Development Company AngularJS took a swift transition to open-source. When Misko Hevery joined Google, he continued to develop Angular JS. The platform began to earn its place by December of 2012 according to Google Trends.
In the year 2015, the potential of AngularJS surpassed other frameworks and offered job placements for many developers. However, AngularJS is not entirely without competition as Facebook came up with ReactJS. Hence, there is a race to show which surpasses the other. But, according to Jeff Schroeder, among the native apps, React elevates mobile app development to higher levels.
Continuous Development in Angular JS
AngularJS has high popularity yet, the developers break backward compatibility on a regular basis. Therefore, the supporters of AngularJS have to learn the AngularJS framework again and again. A critic of AngularJS – Danny Tuppeny, points out that the framework is unstable as it offers short-term support. The developers develop the framework every now and then which can puzzle its users. However, a mobile Web developer by the name of Nene Bodonkor indicates another factor. The frameworks become satisfactory and since they fail to keep up with the market requirements, change becomes crucial.
On the contrary, Yehuda Katz, the creator of EmberJS suggests that the fast-paced lifestyle needs to slow down. Therefore, these constant changes can compel people to reduce and balance their pace. Both, ReactJS from Facebook and EmberJS fight to achieve maximum backward compatibility. Such a characteristic helps these frameworks to come to use for an enterprise. But, AngularJS still has its upper hand over its competitors.
The simple-to-learn design of the Angular Framework with various functions
A legacy system includes few characteristics like old technology that are not compatible with the present systems. These systems do not remain available for purchase from distributors or vendors. These legacy systems cannot update nor patch up by themselves as the developer or vendor stops its maintenance.
The CTO of a mobile and Web app development company Monsoon, Michi Kono agreed on the decisions. But he also commented that the core developers at AngularJS miscommunicated the information. As the AngularJS framework has its uses in Google, they can use the platform for legacy versions and supporting enterprises. According to Michi Kono, AngularJS can promise a safe approach for its use in enterprises. The framework of Angular Development Company USA makes learning simple as it lacks strong convention opinions. The framework is easy for developers to learn and Angular has its applications on other parallel technologies. Vast organizations that have a demand for on-scale development and hiring procedures can use the framework to their advantage.
The low level of Angular appears more as a toolbox than a framework. Such an approach makes Angular useful on a wide variety of utility functions. The developer can use the JavaScript framework to add a single website button through a separate framework. Major companies like Google, Facebook and Microsoft aim to improve JavaScript to match entrepreneur requirements. Since AtScript or the typed JavaScript from Google, will form the backbone of AngularJS 2.0, several developers shall prefer to leverage it.
The Best Fit
AngularJS has several promising aspects for developers from different enterprises to try. But the JavaScript framework undergoes several alterations by its developers. Yet, some of the JavaScript frameworks grab the focus of various users for which they remain in maintenance. Therefore, according to Brian Leroux, the Adobe Web developer, there are two options left. Developers can either imprison themselves within vast rewrites with no forward progress. Or Hire angular developers who can focus their attention to optimize the website architecture. Therefore, developers need to stay up-to-date with the current developments in the web application frameworks like AngularJS.
AngularJS frameworks carry lots of potential in real-time markets. But, the developers need to stay up-to-date to tackle the regular changes in its infrastructure.
#hire angular developers #angular #angular web development #angular development company #angular services #angularjs