Angular 2 Interview Questions and Answers Part 4

16. What is an Angular 2 services?

Answer:

Angular 2 Services are JavaScript functions. It is used when a common functionality needs to be provided to various modules, i.e. database functionality that could be reused among various modules. Services allow for greater seperation of concerns for your application and better modularity by allowing you to extract common functionality out of components.

Following are the steps to create the services in Angular 2.

  • Create the Service File
    name.service.ts

  • Import the injectable member
    import { Injectable } from '@angular/core';

  • Add the Injectable Decorator
    @Injectable()

  • Export the Services Class
    export class ExampleService {
          someMethod() {
            return 'Welcome!';
        }
    }

17. What are the features of Angular 2 Service?

Answer:

Following are the features of services in Angular 2.

  • Services are singleton object i.e. only one instance of service exists throughout the application.
  • Services are capable of returning the data in the form promises or observables.
  • Service class is decorated with @Injectable() decorator.

18. What are the differences between Observables and Promises?

Answer:

Both Observables and Promises come with abstractions that help to deal with asynchronous nature of our application.

Observables:

Observable is just a function that takes an observer and returns a  function. It is nothing more than a specific type of function with a specific purpose.

It accepts an observer: an object with 'next', 'error' and 'complete' methods on it. And returns a cancellation function.

Observer allows to subscribe/unsubscribe to its data stream, emit next value to the observer, notify the observer about errors and inform the observer about the stream completion

Observer provides a function to handle next value, errors and end of stream (ui events, http responses, data with web sockets).

Works with multiple values over time

It is cancel-able/retry-able and supports operators such as map, filter, reduce etc.  

Promise:

A promise represents a task that will finish in the future

Promises is resolved by a value

Promises get rejected by exceptions

Not cancellable and it returns a single value

19. What is CLI in Angular 2?

Answer:

CLI stands for command line interface. The CLI makes it easy to create an Angular JS application.

Angular 2 CLI offers "generate" command. With "generate", you can create perfect components, services, modules, directives, interfaces, and pipes in seconds using only one line of text.

The great thing about the CLI is that it will create some baseline test for your classes as you generate them, making it even easier to write unit tests.

20. How can we achieve Internationalization using Angular 2?

Answer:

It can be achieved using the directive i18n.