Prepare for Angular Interviews with real-life questions. Utilize quizzes and examples to deepen understanding and enhance your skills. Gear up to ace your interview!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


Which command is used to create a new service in Angular?

  1. ng create service service-name

  2. ng generate service service-name

  3. ng add service service-name

  4. ng new service service-name

The correct answer is: ng generate service service-name

The command used to create a new service in Angular is "ng generate service service-name." This command is part of Angular's CLI (Command Line Interface) tool, which provides a simplified way to scaffold different elements of an Angular application, including components, directives, and services. When you use "ng generate service service-name," the Angular CLI performs the following tasks: 1. **File Creation**: It automatically creates the necessary files for the service, including an Angular service file (.ts) and a spec file (.spec.ts) for testing, often placing them in the appropriate directory structure based on your specified path. 2. **Service Registration**: If you create the service in a module, Angular can automatically handle the registration of the new service in that module, allowing for dependency injection to work seamlessly. 3. **Boilerplate Code**: The CLI generates standard boilerplate code that follows best practices, reducing the chances of errors and saving time. Using the other commands mentioned would not achieve the same result. For instance, the possibility of creating a service using "ng create service service-name," "ng add service service-name," or "ng new service service-name" does not align with Angular’s CLI commands and structure, reflecting their specific functionalities