Angular Interview Questions – Part 2

Angular Interview Questions

angular2Binterview2Bquestions

1. What are Angular cli commands? 

Scaffold
Usage
ng g component my-new-component
ng g directive my-new-directive
ng g pipe my-new-pipe
ng g service my-new-service
ng g class my-new-class
ng g guard my-new-guard
ng g interface my-new-interface
ng g enum my-new-enum
ng g module my-module

2. Tell me about the files Angular projects creates and uses on ng-new?

angular-cli.json

So automating the angular application from cli requires angular-cli.json to loads its configuration.

Main.ts

Main entry point where angular runs the application with below code.
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

tsconfig.json 

Browsers can’t execute TypeScript directly. Typescript must be “transpiled” into JavaScript using the tsc compiler, tsconfig.json— file is required for TypeScript compiler configuration.

package.json

Your project information that NPM uses. This can be used to add new libraries that you can use in your project.

3. Which files Angular builds on ng-serve or ng-build?

inline.bundle.js

This is a webpack loader. A tiny file with Webpack utilities that are needed to load the other files.

main.bundle.js

This is where the action happens. This file contains all your code.

polyfills.bundle.js

Polyfills in basic language are extra lines of code which make your application compatible for different browsers. The code we write is mostly in ES6 and is not compatible with IE or firefox and needs some environment setups before being able to be viewed or used in these browsers. So, the polyfills takes up the task abd do these low level setups for you.

vendor.bundle.js

This file contains any libraries imported into your app (app.module), including the Angular libraries. Third party libraries imported into your app also get compiled into this file (e.g. bootstrap js).

Main.bundle.js.map

*.map files are used to debug the files and these files will not be created wen we build ng build –prod

4. What is deference between Observable and Promise?

4. Observable vs Promise

Single value vs multiple values
Promises are most commonly used to handle HTTP requests. In this model, you make a request and then wait for a single response. You can be sure that there won’t be multiple responses to the same request.
Promises actually enforce this semantics. You can create a Promise, which resolves with some value:

const numberPromise = new Promise((resolve) => {
    resolve(5);
});
numberPromise.then(value => console.log(value));
// will simply print 5 

But attempting to resolve Promise again with another value will fail. Promise is always resolved with the first value passed to the resolve function and ignores further calls to it:

const numberPromise = new Promise((resolve) => {
     resolve(5);
     resolve(10);
 });
 

numberPromise.then(value => console.log(value));
// still prints only 5

On the contrary, Observables allow you to resolve (or, as we say, “emit”) multiple values. Here is how it would look:

const numberObservable = new Observable((observer) => {
     observer.next(5);
     observer.next(10);
 });
 numberObservable.subscribe(value => console.log(value));
 // prints 5 and 10

Eager vs lazy

const promise = new Promise(() => {
     console.log('I was called!');
 });

This will print “I was called!” to the console immediately. On the contrary test following, Observable based, code:

const observable = new Observable(() => {
     console.log('I was called!');
 });

This time nothing happens. This is because while Promises are eager, Observables are lazy. Function passed to Observable constructor gets called only when someone actually subscribes to an Observable:

observable.subscribe();
// just now "I was called!" gets printed

Multicast vs either unicast or multicast
What would happen if someone else would call then as well, few moments later?

const waitOneSecondPromise = new Promise((resolve) => {
    console.log('I was called!'); 
 setTimeout(() => resolve(), 1000);
   });
waitOneSecondPromise.then(doSomething);
 // 500ms passes
waitOneSecondPromise.then(doSomethingElse);

In previous example, even though then was called twice, you would see “I was called!” logged only once to the console, proving that there is only one instance of setTimeout clock. Promise are by default MultiCast

const waitOneSecondObservable = new Observable((observer) => {
    console.log('I was called'); 
    setTimeout(() => observer.next(), 1000);
});

Both doSomething and doSomethingElse functions will be called one second from the moment they were passed to subscribe. If you look in the console, you will see “I was called!” printed to console twice so Observables are by default UniCast. We can make Observale Multicast by using share().

const sharedWaitOneSecondObservable = waitOneSecondObservable.share();

5. What is Typings in Angular?
6. What is *.d.ts file in Angular?

Typings are actually TypeScript Definitions that provide for example Intellisense support for Visual Studio.
Go to Npm/types website and find the framework which we want to include typings and get its typing name.
Run the command npm install –save @type/jquery

This command will install the jqeury and give us the autosense and remove the compilation errors of jquery code used in the html page. And it will also create a *.d.ts file which will hold the type defination for jquery which we can use in our code.

7. What is Feature Module in Angular?

With feature modules, you can keep code related to a specific functionality or feature separate from other code.
Generate new module from angular cli
ng generate module CustomerDashboard
New Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: []
})
export class CustomerDashboardModule { }

App Module

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    CustomerDashboardModule // add the feature module here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

8. How to do the lazy loading of feature module?

You can lazy load a module with the below loadChildren feature of Routes.

const routes: Routes = [
    { path: 'customer-list',
      loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }
    ];

9. What is CORS?10. How to enable CORS in Spring Boot to communicate with Angular application?

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser.  Additionally, for HTTP request methods that can cause side-effects on server’s data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers “preflight” the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon “approval” from the server, sending the actual request with the actual HTTP request method.
Handling a simple request in CORS

HTTP Request:

POST /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.bob.com

The good news is that browsers don’t expect CORS response headers on same-origin requests. The response to a same-origin request is sent to user, regardless of whether it has CORS headers or not. However, if your server code returns an error if the Origin doesn’t match a list of allowed domains, be sure to include the origin the request comes from.
Here’s a valid server response; the CORS-specific headers are bolded

HTTP Response:

Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8

All CORS related headers are prefixed with “Access-Control-“. Here’s some more details about each header.

What is Preflight Request in CORS?

The browser first issues a preflight request, which is like asking the server for permission to make the actual request. Once permissions have been granted, the browser makes the actual request. The browser handles the details of these two requests transparently.
JavaScript: ( PUT / DELETE)

var url = 'http://api.alice.com/cors';
var xhr = createCORSRequest('PUT', url);
xhr.setRequestHeader(
    'X-Custom-Header', 'value');
xhr.send();

Preflight Request:

OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

In above response if browser gets the response for Origin and Access-Control-Request-Method then it will send the request to another server.

How to enable CORS in Spring application?

CORS on Apache Server
To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:

Header set Access-Control-Allow-Origin "*"

CORS in Spring Boot

@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
        System.out.println("==== in greeting ====");
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

10. What is AOT in Angular?11. What is Ahead Of Time Compiler in Angular12. What is difference between JIT and AOT in Angular?

Every Angular application requires a compilation process before they can run in the browser: the enriched components and templates provided by Angular cannot be understood by the browser directly.   The initial compiler in Angular 1.x and Angular 2 is called JiT (Just-in-Time) compiler. As for AoT, it stands for the Ahead-of-Time compiler that was recently introduced in Angular. Compared to the JiT compilation performed by Angular at run-time. The initial compiler in Angular 1.x and Angular 2 is called JiT (Just-in-Time) compiler. As for AoT, it stands for the Ahead-of-Time compiler that was recently introduced in Angular.

Characteristic
JiT(Just-in-Time)
AoT
Compilation target
Browser
Server
Compilation context
Runtime
Build
Bundle size
Huge (~1.2 MB)
Smaller (~400 KB)
Execution Performance
Better
Startup time
Shorter