0
0
Angularframework~30 mins

Creating a service with CLI in Angular - Try It Yourself

Choose your learning style9 modes available
Creating a service with CLI
📖 Scenario: You are building a simple Angular app that needs to fetch user data. To keep your code clean and organized, you want to create a service that handles this data fetching.
🎯 Goal: Create an Angular service using the Angular CLI. This service will be ready to use for fetching user data in your app.
📋 What You'll Learn
Use Angular CLI to generate a service named user
The service file should be named user.service.ts
The service should be provided in the root injector
The service class should be named UserService
💡 Why This Matters
🌍 Real World
Services in Angular help organize code that deals with data fetching, business logic, or shared state. Using the CLI to generate services speeds up development and ensures consistent structure.
💼 Career
Knowing how to create and use Angular services is essential for building scalable and maintainable Angular applications, a common requirement in frontend developer roles.
Progress0 / 4 steps
1
Generate the user service using Angular CLI
Open your terminal and run the Angular CLI command to generate a service named user. This will create the service files including user.service.ts.
Angular
Need a hint?

Use ng generate service user or the shorthand ng g s user.

2
Check the generated service file for the class and decorator
Open the generated user.service.ts file and verify it contains the @Injectable decorator with providedIn: 'root' and a class named UserService.
Angular
Need a hint?

The service should have @Injectable({ providedIn: 'root' }) and a class named UserService.

3
Add a method to the service to simulate fetching user data
Inside the UserService class, add a method named getUser() that returns an object with id: 1 and name: 'Alice'.
Angular
Need a hint?

Define getUser() inside UserService that returns the user object.

4
Use the service in a component by injecting it
In your component's constructor, inject the UserService by adding a parameter named userService of type UserService. This prepares the component to use the service.
Angular
Need a hint?

Inject UserService in the component constructor by adding userService: UserService as a parameter.