Subscribe Notify pattern

Hi,

I have created a Subscribe Notify pattern, that greatly simplifies dealing with Observables (eg. for HttpClient), in your component.

The pattern is implemented by a Notification Service which subscribes to the Observable and wires up the data & error received, to streams.

**Notification Service**

These streams (data$ & error$) are assigned to local variables (employees$ & error$) in your component.

These variables re-render the mark up every time they are notified & updated with new data or error.

component.ts

private readonly notificationService = inject(NotificationService<Employee[]>);

private readonly employeeApiService = inject(EmployeeApiService);

public employees$ = this.notificationService.data$;
public error$ = this.notificationService.error$;

getEmployeesByName(searchName: string) {
     // Fetch employees by name.
     // The employeeApiService method returns an Observable<Employee[]>.
     // The employees$ stream will be notified and updated with the data.
     // The error$ stream will be notified and updated with the error if any.
     this.notificationService.subscribe
     (
        this.employeeApiService.getEmployeesByName(searchName)
     );
}

component.html

@if (error$ | async) {
   <div style="color:red">{{(error$ | async)?.message}}</div>
}

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Total Leave Days</th>
        </tr>
    </thead>
    <tbody>
        <!-- Loop through the employees$ stream -->
        @for (employee of employees$ | async; track employee.id) {
            <tr>
                <td>{{ employee.name }}</td>
                <td>{{ employee.totalLeaveDays }}</td>
            </tr>
        }
    </tbody>
</table>

Real easy to implement in your solution.

Read more

Leave a Reply