All quizzesEasy
Injectable & Providers
Preview — 3 of 10 questions
What is the primary purpose of an Angular service?
javascript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly apiUrl = '/api/users';
constructor(private http: HttpClient) {}
getUser(id: string): Observable<User> {
return this.http.get<User>(`${this.apiUrl}/${id}`);
}
}ATo define the HTML structure of a reusable UI element
BTo configure routing between pages
CTo encapsulate reusable business logic, data access, or shared state that is not tied to a specific component
DTo define animation transitions between components
What does @Injectable() on a class do?
javascript
@Injectable({
providedIn: 'root', // singleton, available app-wide, tree-shakeable
})
export class AuthService {
private isLoggedIn = false;
login(token: string) { /* ... */ }
logout() { /* ... */ }
}AIt makes the class available as an HTML element
BIt marks the class so that Angular's DI system can create and inject instances of it
CIt registers the class as a route guard
DIt enables two-way binding on the class properties
What does providedIn: 'root' in @Injectable mean?
javascript
@Injectable({ providedIn: 'root' })
export class AnalyticsService {
track(event: string) { /* ... */ }
}
// Any component or service can now inject it:
@Component({ ... })
export class PageComponent {
constructor(private analytics: AnalyticsService) {}
}AThe service is provided only to the root component, not its children
BThe service is registered with the root injector, making it a singleton available throughout the entire application
CThe service can only be provided from the AppModule
DThe service is lazy-loaded with the root route
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.