DEV Community

Shantanu
Shantanu

Posted on • Edited on

Subscribe Notify pattern

Hi,

I have created a Subscribe Notify pattern, that greatly simplifies dealing with Observables (eg. for HttpClient), in your Angular 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)
     );
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Real easy to implement in your solution.

Read more...

Top comments (1)

Collapse
 
nevodavid profile image
Nevo David

Growth like this is always nice to see. Kinda makes me wonder - what keeps stuff going long-term? Like, beyond just the early hype?