DEV Community

Angular Interview - Implement Data Reload

Eduard Krivanek on January 31, 2024

When interviewing into Angular related jobs, one question I used to get asked, is “Demonstrate a simple data reloading when user clicks on a button...
Collapse
 
teej107 profile image
teej107 • Edited

The imperative approach suffers from a race condition when the "Load Quote" button is clicked (again) before the previous api call is received. That is why I prefer the declarative approach but your example could be greatly simplified.

@Component({
  selector: 'app-button-click-reactive',
  template: `
    <div class="wrapper">
      <div class="wrapper-text">
        Loaded Quote: {{ (loadedQuote$ | async)?.content }}
      </div>

      <div class="wrapper-action">
        <button type="button" (click)='onQuoteLoad()'>Load Quote</button>
      </div>
    </div>
  `,
  standalone: true,
  imports: [CommonModule],
})
export class ButtonClickReactiveComponent {
  private quotesApiService = inject(QuotesApiService);

  loadedQuote$= this.quotesApiService.getRandomQuote().pipe(share());

  onQuoteLoad() {
    this.loadedQuote$ = this.quotesApiService.getRandomQuote().pipe(share());
  }
}
Enter fullscreen mode Exit fullscreen mode

Since the Observable is being re-assigned as a result of the click output event in the html template, it automatically plays nice with change detection.

Collapse
 
krivanek06 profile image
Eduard Krivanek

you are right, you approach will work. It just depends if you want to use the async pipe in the template or signals. I agree with the declarative approach, for me it wins because it is easier to read.