DEV Community


Posted on

Closures & Angular

During the interview, most of the people are able to answer when asked about Closures and their general examples. But when asked about the same if they have used or seen it anywhere in their angular application most of them failed to provide an example. So I thought to document a basic example of closure in Angular.
Reiterating the definition of Closure as per MDN. Closures.


A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Now breaking up the definition for better understanding.
A closure gives you access to an outer function’s scope from an inner function.
So basically after execution of the outer function, the inner function can remember the scope (e.g. if there are any variables in the outer function the inner function can access them).
So, in Angular, we usually subscribe to any API call inside the ngOnInit function. Something like the below example.

ngOnInit() {
    this.api.get('users?page=1').subscribe(res => {
      this.users = res;
      console.log('data response', this.users);
    }, error => {
Enter fullscreen mode Exit fullscreen mode

Here the subscribe and error functions are acting as inner functions and the ngOnInit is acting as an outer function. And we can access any variables or methods of the component using this keyword. This means it remembers the scope of the outer function.

PS: This is my first blog, apologies if I have made any mistakes. Hope you have liked this one.

Top comments (0)