Skip to main content

angular start 4

 


LazyLoading:

By default, NgModules are eagerly loaded. This means that as soon as the application loads, so do all the NgModules, whether they are immediately necessary or not. For large applications with lots of routes, consider lazy loading —a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.

ng generate module customers --route customers --module app.module

Because the new module is meant to be lazy-loaded, the command does not add a reference to it in the application's root module file, app.module.ts. Instead, it adds the declared route, customers to the routes array declared in the module provided as the --module option.


Lazy loading is an important Angular feature that helps to reduce the initial load time since it loads only the necessary files first. Other required modules are loaded on demand when you navigate to their particular route. Now, you can take advantage of this feature to improve your app's load time.


Routing:
In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. As users perform application tasks, they need to move between the different views that you have defined.

Import RouterModule and Routes into your routing module.



import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; // CLI imports router

const routes: Routes = []; // sets up routes constant where you define your routes
const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, ];
// configures NgModule imports and exports
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


<h1>Angular Router App</h1>
<!-- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in  AppRoutingModule) -->
<nav>
  <ul>
    <li><a routerLink="/first-component" routerLinkActive="active" ariaCurrentWhenActive="page">First Component</a></li>
    <li><a routerLink="/second-component" routerLinkActive="active" ariaCurrentWhenActive="page">Second Component</a></li>
  </ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>

The order of routes is important because the Router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. List routes with a static path first, followed by an empty path route, which matches the default route. The wildcard route comes last because it matches every URL and the Router selects it only if no other routes match first.

observable:
Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.

hat is RxJS

The RxJS (Reactive Extensions Library for JavaScript) is a javascript library, that allows us to work with asynchronous data streams.

Angular uses the RxJS library heavily in its framework to implement Reactive Programming. Some of the examples where reactive programming used are:

  • Reacting to an HTTP request in Angular
  • Value changes / Status Changes in Angular Forms
  • The Router and Forms modules use observables to listen for and respond to user-input events.
  • You can define custom events that send observable output data from a child to a parent component.
  • The HTTP module uses observables to handle AJAX requests and responses.

The RxJs has two main players

  1. Observable
  2. Observers ( Subscribers)

What is an Observable in Angular?

An Observable is a lazily evaluated computation that can synchronously or asynchronously return zero to (potentially) infinite values from the time it’s invoked onwards. In other words, Observable is a function that converts the ordinary stream of data into an observable stream of data.

Observable emits the value from the stream asynchronously. It emits the complete signals when the stream completes or an error signal if the stream errors out.

Observables are declarative. You define an observable function just like any other variable. The observable starts to emit values only when someone subscribes to it. Subscribing to an Observable is analogous to calling a Function.

Who are observers (subscribers)?

The Observable on its own is useless unless someone consumes the value emitted by the observable. We call them observers or subscribers.

The observers communicate with the Observable using callbacks.

The observer must subscribe with the observable to receive the value from the observable. While subscribing, it optionally passes the three callbacks. next()error() & complete().

obs = new Observable((observer) => {
console.log(“Observable starts”)
observer.next(“1”)
observer.next(“2”)
observer.next(“3”)
observer.next(“4”)
observer.next(“5”)
})

The variable obs is now of the type of Observable.

ngOnInit() {
this.obs.subscribe(
val => { console.log(val) }, //next callback
error => { console.log("error") }, //error callback
() => { console.log("Completed") } //complete callback
)
}


 
Dependecy injector:
Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.

Imagine there is a class called HeroService that needs to act as a dependency in a component.

The first step is to add the @Injectable decorator to show that the class can be injected.

@Injectable()
class HeroService {}
  • At the application root level, which allows injecting it into other classes in the application. This can be done by adding the providedIn: 'root' field to the @Injectable decorator:
@Injectable({
  providedIn: 'root'
})
class HeroService {}

When you provide the service at the root level, Angular creates a single, shared instance of the HeroService and injects it into any class that asks for it. Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service from the compiled application if it isn't used, a process known as tree-shaking.

Injecting a dependency

The most common way to inject a dependency is to declare it in a class constructor. When Angular creates a new instance of a component, directive, or pipe class, it determines which services or other dependencies that class needs by looking at the constructor parameter types. For example, if the HeroListComponent needs the HeroService, the constructor can look like this:

@Component({  })
class HeroListComponent {
  constructor(private service: HeroService) {}
}

When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector creates one using the registered provider and adds it to the injector before returning the service to Angular.


Sharing modules

Creating shared modules allows you to organize and streamline your code. You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application





Comments

Popular posts from this blog

Node.js: Extract text from image using Tesseract.

In this article, we will see how to extract text from images using Tesseract . So let's start with this use-case, Suppose you have 300 screenshot images in your mobile which has an email attribute that you need for some reason like growing your network or for email marketing. To get an email from all these images manually into CSV or excel will take a lot of time. So now we will check how to automate this thing. First, you need to install Tesseract OCR( An optical character recognition engine ) pre-built binary package for a particular OS. I have tested it for Windows 10. For Windows 10, you can install  it from here. For other OS you make check  this link. So once you install Tesseract from windows setup, you also need to set path variable probably, 'C:\Program Files\Tesseract-OCR' to access it from any location. Then you need to install textract library from npm. To read the path of these 300 images we can select all images and can rename it to som...

Globant part 1

 1)call,apply,bind example? Ans: a. call Method: The call method is used to call a function with a given this value and arguments provided individually. Javascript code: function greet(name) {   console.log(`Hello, ${name}! I am ${this.role}.`); } const person = {   role: 'developer' }; greet.call(person, 'Alice'); // Output: Hello, Alice! I am developer. In this example, call invokes the greet function with person as the this value and passes 'Alice' as an argument. b. apply Method: The apply method is similar to call, but it accepts arguments as an array. Javascript code: function introduce(language1, language2) {   console.log(`I can code in ${language1} and ${language2}. I am ${this.name}.`); } const coder = {   name: 'Bob' }; introduce.apply(coder, ['JavaScript', 'Python']); // Output: I can code in JavaScript and Python. I am Bob. Here, apply is used to invoke introduce with coder as this and an array ['JavaScript', 'Pyt...

Globlant part 2

 1)JWT token:           const jwt = require ( 'jsonwebtoken' ); A JWT token consists of three parts separated by dots ( . ): Header : Contains metadata about the type of token and the hashing algorithm used. Payload (Claims) : Contains the claims or statements about the subject of the token, such as user ID, roles, etc. Signature : Verifies that the sender of the JWT is who it says it is and ensures that the message wasn't changed along the way. It is header +payload +secret key. Methods: const newToken = jwt. sign (payload, secretKey, { expiresIn : '1h' }); Use verify() when you need to ensure the token's integrity and authenticity. Use decode() when you only need to extract information from the token and don't need to verify its signature. 2)Window ,this,global: In nodejs this and global refers to same global methods and varibales just that no dom related things that are in window. In nodejs no window. 3)a.getSum(); // Define the custom method getSu...