Angular › Angular Style Guide & Best Practices
What is the single responsibility principle and how does it apply to writing Angular components and services?
IntermediateAnswer
The single responsibility principle means each component or service should do just one clear thing, such as displaying a single piece of information or handling one specific type of data request. Breaking a large component into smaller, focused ones, and keeping business logic in services rather than components, makes the code easier to read, test, and reuse.
// One large component doing too much
@Component({ selector: 'app-user-page' })
export class UserPageComponent { /* fetches data, shows profile, shows posts, shows settings */ }
// Split into smaller, focused pieces, with logic moved to a service
@Component({ selector: 'app-user-page' })
export class UserPageComponent {
constructor(private userService: UserService) {}
}Real-world example A team breaks apart one giant component that both fetched data and rendered a complex layout into a dedicated service handling the data fetching and several smaller, focused components handling just the display.