DEV Community

Shantanu
Shantanu

Posted on • Edited on

1 1 1

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...

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

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?