Hone logo
Hone
Problems

Angular Service Provider Challenge

This challenge focuses on a fundamental concept in Angular: dependency injection and service providers. You will create and configure a service that can be injected into different parts of an Angular application, demonstrating your understanding of how to make data and functionality accessible across your app. This is a cornerstone of building maintainable and scalable Angular applications.

Problem Description

Your task is to create a simple Angular service named UserService that manages user data. This service should be provided at the application root level, ensuring a single instance is available throughout the entire application.

What Needs to Be Achieved:

  1. Create an Angular service class named UserService.
  2. Implement a method within UserService to fetch a hardcoded user object.
  3. Configure UserService to be provided at the application's root level using providedIn: 'root'.
  4. Create an Angular component (UserProfileComponent) that injects UserService.
  5. In UserProfileComponent, use the injected UserService to retrieve user data and display it.

Key Requirements:

  • The UserService should be a standard Angular service.
  • The providedIn: 'root' configuration is mandatory.
  • The UserProfileComponent should demonstrate the injection and usage of the UserService.

Expected Behavior:

When the UserProfileComponent is displayed, it should fetch and show the user's information (e.g., name and email) provided by the UserService.

Important Edge Cases:

  • Consider how the service would behave if it were provided at a different level (though for this challenge, root is specified).
  • Ensure proper import statements are used for services and components.

Examples

Example 1:

  • Input: N/A (This is a structural and implementation challenge, not input/output based in the traditional sense.)
  • Output: A running Angular application where the UserProfileComponent displays hardcoded user details fetched from the UserService.
  • Explanation: The UserService is created and configured. The UserProfileComponent injects this service and calls its method to get user data, which is then rendered.

Constraints

  • Angular CLI version 12 or higher is recommended.
  • Solutions should be implemented using TypeScript.
  • The UserService should be an injectable service using the @Injectable() decorator.

Notes

  • The providedIn: 'root' option automatically registers the service in the application's root injector, making it a singleton service available throughout the app without needing to be added to any module's providers array.
  • Think about how you would structure the UserService to be reusable and extensible.
  • For this challenge, the user data can be hardcoded within the service. In a real-world scenario, this data would likely come from an API call.
Loading editor...
typescript