Chapters Premium | Chapter-4: Rest API and Bootstrap.
Note: For all 10 chapters, please refer to the navigation section above.

Chapter 4: Rest API and Bootstrap.
Welcome to ReadioBook.com, in this readiobook we are going to cover 21 Interview questions based on Angular and Bootstrap.

Question: What are the ways to add Bootstrap in Angular project?

Answer: To add Bootstrap to an Angular project, you have a few different methods at your disposal:

- Using Angular CLI: You can add Bootstrap by using the Angular CLI. This is the recommended approach since it keeps the configuration clean and easy to manage. You would use the following command:
ReadioBook.com Angular Interview Questions And Answer 001
This command will automatically update your Angular project with the correct Bootstrap and ‘ng-bootstrap’ dependencies.

- Manual Installation: You can manually install Bootstrap by running:
ReadioBook.com Angular Interview Questions And Answer 002

Then, you would include Bootstrap in your styles in the ‘angular.json’ file:
ReadioBook.com Angular Interview Questions And Answer 003

- Using a CDN: If you prefer not to include Bootstrap in your project dependencies, you can link to it via a CDN. You would add the Bootstrap CDN link to the ‘index.

html’ file in your project:
ReadioBook.com Angular Interview Questions And Answer 005
Each of these methods has its advantages. The Angular CLI method offers a more integrated and Angular-specific approach, manual installation gives you more control over the version and configuration, and the CDN is the quickest way to get started without modifying your project setup.

In practice, here's a simple code example of how you might use Bootstrap in your Angular component after installation:
ReadioBook.com Angular Interview Questions And Answer 006
In this code, ‘container’ and ‘btn btn-primary’ are Bootstrap classes that will style the ‘div’ and ‘button’ elements accordingly.


Question: What do you mean by CRUD operations?

Answer: CRUD operations refer to the four basic operations you can perform on data in a database or a data storage system. They stand for Create, Read, Update, and Delete.

- Create: Adding new records. In Angular, you might use a service to post data to an API, like so:
ReadioBook.com Angular Interview Questions And Answer 007

- Read: Retrieving data.

With Angular, this typically involves making a GET request:
ReadioBook.com Angular Interview Questions And Answer 008

- Update: Modifying existing records. You would usually send a PUT request:
ReadioBook.com Angular Interview Questions And Answer 010

- Delete: Removing records. This is done via a DELETE request:
ReadioBook.com Angular Interview Questions And Answer 012
These operations form the backbone of many applications, allowing users to manage their data effectively.
In an Angular context, you typically perform these operations through services that make HTTP requests to a backend API.

Question: What is loading component in Angular?

Answer: In Angular, a loading component is typically a visual indicator that you present to users while waiting for data to be loaded or a computation to be completed. It's not a specific feature within the Angular framework itself, but rather a common design pattern.
For example, you might have a spinner or a progress bar that you display when you make an asynchronous call to fetch data from an API.
You show this component to let the user know that the application is working and they need to wait.
Here's a simple example in Angular. Imagine we have a ‘LoadingComponent’ that simply displays a message like "Loading...":
ReadioBook.com Angular Interview Questions And Answer 013

You would include this component in the template of your parent component where the data loading is taking place, and use ‘*ngIf’ to conditionally show it based on whether the data is still loading:
ReadioBook.com Angular Interview Questions And Answer 014
In this example, ‘isLoading’ would be set to ‘true’ when you start your data fetch, and you'd set it to ‘false’ when the data loading is complete.
The ‘LoadingComponent’ will show when ‘isLoading’ is ‘true’, and hide when it's ‘false’.

Question: What is Angular Development Server?

Answer: The Angular Development Server, commonly referred to as ‘ng serve’, is a built-in local server that comes with the Angular CLI. When you’re working on an Angular application, you can use this server to serve your application locally for development and testing purposes. It watches for file changes and automatically reloads the application, making the development process more efficient.

For example, after making changes to your code, you don't need to manually refresh your browser; the development server does that for you. Here's how you might use it:
- Open your command line interface.- Navigate to your Angular project directory.- Run the command ‘ng serve’.

This will compile your application and make it accessible in a browser at ‘http: //localhost:4200’. The development server also provides basic logging that can be helpful for debugging.


Question: What is ReactiveFormsModule used for?

Answer: ReactiveFormsModule in Angular is used to handle form inputs and changes through an observable-based approach. It allows you to create forms in a more flexible and scalable way, compared to the Template-Driven approach.
For instance, if you're creating a login form, you would first import the ‘ReactiveFormsModule’ from ‘@angular/forms’ in your module, and then in your component, you'd create a ‘FormGroup’ to keep track of the form's state.

Here's a quick example of how you might set up a simple login form:
ReadioBook.com Angular Interview Questions And Answer 016
In this code, ‘FormGroup’ and ‘FormControl’ are used to create a form model that is reactive and can adapt to user input dynamically. Validators are applied directly to form controls, which can validate the input synchronously or asynchronously.


Question: What do you understand as 'model' in UI applications?

Answer: In UI applications, the term 'model' generally refers to the domain-specific representation of the information on which the application operates. It's the part of the application that handles the logic for the application's data domain. The model directly manages the data, logic, and rules of the application and represents the core data structures and services with which the UI interacts.

For instance, if we're working with Angular, the model could be a TypeScript class that defines the structure of data and possibly includes methods to operate on that data. Here's a simple example of a model in an Angular application:
ReadioBook.com Angular Interview Questions And Answer 017
This ‘User’ class serves as a model for user data within the application.
It defines what a user is in the context of the application, with a unique identifier, a name, and an email address. This model can be used throughout the application to represent and manipulate user data.

Question: What is FormGroup and FormBuilder?

Answer: FormGroup is a fundamental concept in Angular that represents a group of form controls. It aggregates the values of each child FormControl into one object, with each control's name as the key. It also tracks the state of its controls, such as whether they have been modified or if the value is valid, providing a way to handle form validation.

FormBuilder is a syntactic sugar service that simplifies the creation of FormGroup and FormControl instances. It provides methods like ‘group’, ‘control’, and ‘array’ to create form control objects without newing up instances manually. Here's an example of how to use both in an Angular component:
ReadioBook.com Angular Interview Questions And Answer 019
In this example, ‘FormBuilder’ is injected via the constructor and used to create a ‘FormGroup’ with two form controls for first and last names, both with required validators and a minimum length validator.


Question: What is Error Handling and how you achieve the same in Angular app?

Answer: Error handling in Angular is a systematic approach to dealing with unexpected errors that may occur during the execution of an application. It's crucial because it helps maintain a good user experience even when things go wrong. In Angular, error handling is often achieved using a combination of try-catch blocks, error handling services, and global error handlers.
When it comes to services or asynchronous operations like HTTP requests, Angular has RxJS Observables, which provide a method called ‘catchError’ as part of its pipeable operators. This operator can intercept errors and provide a way to handle them.
Here's a simple code example showing how you might handle errors in an Angular service that makes HTTP requests:
ReadioBook.com Angular Interview Questions And Answer 021
In this example, the ‘getData’ method fetches data from an API and uses the ‘catchError’ operator to intercept any errors that occur during the HTTP request.
The ‘handleError’ method then logs the error and returns a user-friendly error message. This method can also be improved to handle different types of errors appropriately.

Question: What is the use of 'pipe' directive?

Answer: The ‘pipe’ operator in Angular is a method on observables that you use to compose operators, which are functions that take observable input and return an observable output. In the context of error handling, particularly with the ‘catchError’ operator, it allows you to intercept and handle errors that occur within an observable stream.

For example, when making an HTTP request, you might want to catch any errors that occur if the request fails. The ‘catchError’ operator can be used within a ‘pipe’ to handle these errors gracefully. Here's a basic code example that shows how you might use ‘catchError’ inside a ‘pipe’:
ReadioBook.com Angular Interview Questions And Answer 023
In this example, if the HTTP request fails, the ‘catchError’ function logs the error and returns an empty array as a fallback so that the observable stream remains functional.


Question: What is the use of httpOptions?

Answer: In Angular, ‘httpOptions’ is typically used to specify headers for HTTP requests made through the HttpClient service. When you're making requests to a server, you often need to include metadata such as content type or authorization tokens. The ‘httpOptions’ object allows you to define these headers.

Here's a practical scenario: suppose you're sending JSON data to a server. In that case, you would set the ‘Content-Type’ header to ‘application/json’. Similarly, if you're dealing with authentication, you might include an ‘Authorization’ header. Here's a brief code example:
ReadioBook.com Angular Interview Questions And Answer 025
In this snippet, we first import ‘HttpClient’ and ‘HttpHeaders’ from the Angular common HTTP package.
We then create an ‘httpOptions’ object with a headers property. This property is an instance of ‘HttpHeaders’ and includes our desired headers. Finally, in the ‘addHero’ method, we make a POST request where we pass ‘httpOptions’ as the third argument to include our headers in the request.

Question: What do you mean by authentication?

Answer: Authentication means recognizing if the user who tries to enter the application is who they claim to be.


Question: What do you mean by authorization?

Answer: Authorization refers to restricting the user’s access to certain parts of the application, according to their level of permission.


Question: What is Auth0?

Answer: Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. It's essentially a third-party service that abstracts the complexity of securing your application, allowing you to implement various authentication and authorization flows with minimal setup.

For example, in an Angular application, you can integrate Auth0 by installing its SDK and using it to handle user authentication. Here's a basic code snippet to illustrate how you might set up Auth0 in an Angular service:
ReadioBook.com Angular Interview Questions And Answer 027
In this snippet, ‘AuthService’ initializes the Auth0 client and provides a login method that redirects the user to the Auth0 hosted login page.
Once the user logs in, they are redirected back to your application where you can handle the authentication response. This is a very simplified example, and in a real application, you'd include more functionality for handling user sessions, getting user profiles, and securing API calls.

Question: If you are using auth-0 for authentication in your angular app. What all you need to implement to achieve end to end authentication?

Answer: In an Angular application, implementing end-to-end authentication with Auth0 involves several steps. Firstly, you need to configure Auth0 on the service side. You would start by creating an Auth0 account and setting up an application to get the necessary domain and client ID.
On the Angular side, you would begin by installing the Auth0 SDK, which is typically done via npm.

The command would be something like ‘npm install @auth0/auth0-angular’. Once installed, you'll need to configure the Angular module to use Auth0 by providing the domain and client ID in the forRoot method of the Auth0 module. Here's a snippet of what that could look like in your ‘app.module.ts’:
ReadioBook.com Angular Interview Questions And Answer 028
Next, you'll implement a login method that calls ‘auth0.
loginWithRedirect()’. This will handle redirecting the user to the Auth0 hosted login page. Similarly, you'll set up a logout method that calls ‘auth0.logout()’ to clear the user's session. For securing your Angular routes, you'd use the ‘AuthGuard’ provided by Auth0 in your routing module. Here's how it might look in your ‘app-routing.
module.ts’:
ReadioBook.com Angular Interview Questions And Answer 029
On the API side, you'll secure your endpoints by validating the JWT (JSON Web Token) that Auth0 provides upon successful authentication. You'll typically use middleware to validate the token against your Auth0 domain and audience. If you're using Node.js for your backend, you might use the ‘express-jwt’ and ‘jwks-rsa’ libraries to facilitate this.
Remember to handle tokens securely, using HTTPS for your requests and storing tokens appropriately, such as in memory or HttpOnly cookies, and never in local storage. Lastly, you should set up error handling for authentication and authorization errors, both on the client-side and the API side, to inform users of any issues and potentially log these errors for further investigation. This overview should give you a good foundation for an Auth0 implementation in an Angular application, demonstrating both an understanding of the Auth0 platform and the Angular framework.

Question: What is a component and a template in Angular?

Answer: A component in Angular is a fundamental building block of an Angular application. It's essentially a TypeScript class that interacts with the HTML of your application, which is defined by the component's template. The component's class is decorated with ‘@Component’, which provides metadata that determines how the component should be processed, instantiated, and used at runtime.
Components are responsible for handling data and logic, while templates are the HTML views that display this data. The template is linked to the component and defines the markup which Angular transforms into the DOM (Document Object Model). The template's syntax can bind to the component's properties and functions, allowing for a dynamic and responsive user experience.
Here's a simple code example:
ReadioBook.com Angular Interview Questions And Answer 030
In this code snippet, ‘ExampleComponent’ is a component with a property ‘title’. The ‘@Component’ decorator indicates that this class is a component and provides metadata, including a ‘selector’ that defines the custom HTML tag to use for this component, and a ‘template’ that is the HTML view.
In the template, ‘{{ title }}’ is a template expression that Angular will replace with the value of the ‘title’ property from the component.

Question: What is Font Awesome and Vector Graphic, which is preferred and when?

Answer: Font Awesome is a popular icon toolkit used widely in web development. It provides scalable vector icons that can easily be customized — size, color, drop shadow, and anything that can be done with the power of CSS. Vector graphics, on the other hand, refer to the use of polygons to represent images in computer graphics.
Unlike raster graphics, vector graphics are not based on pixel patterns, but instead use paths, which are defined by a start and end point, along with other points, curves, and angles.In terms of preference, it depends on the use case. Font Awesome is preferred when you need icons because it's easy to implement and has a wide variety of icons readily available. It's also convenient because you can control icon styles through CSS. For more complex illustrations, logos, and where scalability without loss of quality is crucial, vector graphics are preferred.
For example, if you want to add a user icon using Font Awesome in an Angular project, you would do something like this after including the Font Awesome library:
ReadioBook.com Angular Interview Questions And Answer 032
This simplicity is what makes Font Awesome a go-to for web developers needing icons.
However, if you're designing a logo that needs to be displayed at various sizes without quality degradation, you would use a vector graphic in SVG format.

Question: What is SVG and SVG format?

Answer: SVG stands for Scalable Vector Graphics. It's an XML-based markup language for describing two-dimensional vector graphics. SVG is essentially to graphics what HTML is to text. SVG images and their related behaviors are defined in XML text files, which means they can be searched, indexed, scripted, and compressed.
Additionally, SVG files are resolution-independent, which makes them infinitely scalable without losing any image quality.
For example, in an Angular application, you can use SVG directly in your templates to create graphics like icons, charts, or illustrations. Here's a simple code snippet that demonstrates how to use an SVG circle in an Angular component:
ReadioBook.com Angular Interview Questions And Answer 034
This snippet would create a yellow circle with a green stroke.
Since it's vector-based, you could scale this SVG image to any size without it becoming pixelated, which is one of the key advantages of SVG.

Question: What is the Local Storage in Angular and why we are using it?

Answer: Local Storage is a web storage object that allows you to store data in key-value pairs on the client's browser without any expiration date. This means the data will persist even after the browser session has ended, unlike session storage which clears the data once the session is closed.
In an Angular application, Local Storage is often used to store user preferences, authentication tokens, or any other data that needs to be accessed across various components without making repeated calls to a backend server.
It's a convenient way to maintain state on the client side.
Here's a simple example of how you could set and get items from Local Storage in an Angular service:
ReadioBook.com Angular Interview Questions And Answer 035
In this service, the ‘setItem’ method is used to save data, ‘getItem’ to retrieve data, ‘removeItem’ to delete a specific key, and ‘clear’ to remove all stored data.
This service can then be injected into any component that needs to interact with Local Storage. It's important to note that Local Storage should not be used for sensitive data as it is accessible from the client side and can pose security risks.

Question: Is Local Storage a good idea or session should be maintained in backend?

Answer: When deciding whether to use local storage or maintain session state on the backend, it's essential to consider the nature of the data and the application's architecture.
Local storage is convenient for storing non-sensitive data that doesn't need to be frequently updated, like user preferences or UI state.

It's client-specific and persists even after the browser is closed and reopened, which can be beneficial for enhancing user experience by remembering user settings or actions. However, local storage has its limitations: it is not recommended for sensitive data because it's accessible through client-side scripts, making it vulnerable to XSS attacks.
Also, there's a storage limit (usually around 5MB).Maintaining session state on the backend is generally more secure and can handle sensitive data better. It's server-controlled, and you can implement various security measures to protect the data. Sessions can also store larger amounts of data and are not as easily accessible by client-side scripts, reducing the risk of XSS attacks.
For example, if you're building an Angular application that needs to store user authentication tokens, you would typically avoid local storage and instead use HTTP-only cookies or store the session on the backend. Here's a code snippet demonstrating how you might save a non-sensitive UI preference, like a theme, to local storage:
ReadioBook.com Angular Interview Questions And Answer 036

And for sensitive data, you would handle it server-side, perhaps like so:
ReadioBook.com Angular Interview Questions And Answer 038
In the Angular service above, ‘http.
get’ would be used to retrieve session data securely from a server endpoint that handles session storage and security.Ultimately, the choice between local storage and backend session management depends on the specific requirements of your application, particularly around security, data persistence, and user experience.

Question: What is AuthGuard?

Answer: AuthGuard is a service in Angular that allows developers to control access to routes or parts of an application based on user authentication or authorization. It's part of Angular's router module and is used to protect routes by implementing one or more guard functions like ‘canActivate’, ‘canActivateChild’, or ‘canLoad’.
For instance, to protect a route so that it's only accessible to logged-in users, you might implement an AuthGuard service that uses ‘canActivate’ to check whether the user is authenticated. If the user is not authenticated, the guard would return ‘false’, preventing navigation to the route, and could redirect the user to a login page.
Here's a basic code example of an AuthGuard:
ReadioBook.com Angular Interview Questions And Answer 040
In this example, ‘AuthService’ would be a custom service that has a method ‘isLoggedIn’ which checks if the user is currently logged in. If the user is not logged in, the guard uses the ‘Router’ service to navigate to the login page.The route guards are only for the UI.
They do not provide protection against access to an API. We must always force authentication and authorization in our APIs.





ReadioBook.com