The facade service pattern helps simplify complex code by hiding details behind a simple interface. It makes your Angular app easier to use and maintain.
0
0
Facade service pattern in Angular
Introduction
When you want to hide complex logic from components.
When multiple services need to be combined into one simple service.
When you want to make your components cleaner and focused only on UI.
When you want to centralize data fetching and state management.
When you want to make testing easier by mocking one service instead of many.
Syntax
Angular
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class FacadeService { constructor(private serviceA: ServiceA, private serviceB: ServiceB) {} getData() { // combine or simplify calls return this.serviceA.getDataA(); } saveData(data: any) { this.serviceB.saveDataB(data); } }
The facade service is an Angular service decorated with @Injectable.
It uses dependency injection to get other services and exposes simpler methods.
Examples
A simple facade that wraps a user service method.
Angular
export class UserFacade { constructor(private userService: UserService) {} getUser() { return this.userService.fetchUser(); } }
This facade combines two services to simplify product and cart actions.
Angular
export class ProductFacade { constructor(private productService: ProductService, private cartService: CartService) {} getProducts() { return this.productService.getAll(); } addToCart(productId: string) { this.cartService.add(productId); } }
Sample Program
This example shows a facade service that hides two services: one for data and one for logging. The component uses only the facade to get data and log actions.
Angular
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { getData() { return 'Data from DataService'; } } @Injectable({ providedIn: 'root' }) export class LoggerService { log(message: string) { console.log('Log:', message); } } @Injectable({ providedIn: 'root' }) export class FacadeService { constructor(private dataService: DataService, private loggerService: LoggerService) {} fetchData() { this.loggerService.log('Fetching data'); return this.dataService.getData(); } } // Usage in a component import { Component } from '@angular/core'; import { FacadeService } from './facade.service'; @Component({ selector: 'app-root', template: `<h1>{{ data }}</h1>` }) export class AppComponent { data = ''; constructor(private facade: FacadeService) { this.data = this.facade.fetchData(); } }
OutputSuccess
Important Notes
Facade services keep your components simple and focused on displaying data.
They help reduce repeated code by centralizing logic.
Use facades to improve testability by mocking one service instead of many.
Summary
The facade service pattern hides complex service logic behind simple methods.
It makes Angular components cleaner and easier to maintain.
Use it to combine multiple services and centralize data handling.