Performance: Facade service pattern
This pattern affects the interaction complexity between components and services, impacting rendering speed and responsiveness by reducing redundant data fetching and change detection triggers.
export class FacadeService { private data$ = new BehaviorSubject<Data | null>(null); constructor(private http: HttpClient) { this.loadData(); } private loadData() { this.http.get<Data>('/api/data').subscribe(data => this.data$.next(data)); } getData() { return this.data$.asObservable(); } } export class ComponentA { data$ = this.facade.getData(); constructor(private facade: FacadeService) {} } export class ComponentB { data$ = this.facade.getData(); constructor(private facade: FacadeService) {} }
export class ComponentA { constructor(private service: DataService) {} ngOnInit() { this.service.getData().subscribe(data => { /* update UI */ }); } } export class ComponentB { constructor(private service: DataService) {} ngOnInit() { this.service.getData().subscribe(data => { /* update UI */ }); } } @Injectable({providedIn: 'root'}) export class DataService { constructor(private http: HttpClient) {} getData() { return this.http.get('/api/data'); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple components call service independently | Multiple subscriptions causing repeated DOM updates | Multiple reflows triggered per component update | Higher paint cost due to frequent UI changes | [X] Bad |
| Facade service shares single data stream | Single subscription source with shared updates | Single reflow triggered for shared data update | Lower paint cost with batched UI updates | [OK] Good |
What is the main purpose of using a Facade Service in Angular?
Which of the following is the correct way to inject a facade service MyFacadeService into an Angular component constructor?
private and type MyFacadeService, which is correct.Given this facade service method:
getUserName(): Observable<string> {
return this.userService.getUser().pipe(
map(user => user.name)
);
}What will the component receive when subscribing to getUserName()?
Identify the error in this facade service method:
fetchData() {
this.apiService.getData().subscribe(data => {
this.data = data;
});
return this.data;
}this.data is not set immediately.this.data immediately, likely undefined before data arrives.You want to create a facade service that combines data from UserService and SettingsService and exposes a single observable userSettings$. Which approach correctly implements this?
class UserSettingsFacade {
userSettings$: Observable<UserSettings>;
constructor(private userService: UserService, private settingsService: SettingsService) {
// Fill in here
}
}combineLatest to emit latest values from both observables together.map operator to create an object with user and settings properties.Pass the test and this pattern moves unknown