Sign up with your email address to be the first to know about new products, VIP offers, blog features & more.

RxJS Reactive Approach CHEAT SHEET

Define a data type (interface or class)

// ipatient.ts

export interface IPatient {
    id: number;
    name: string;
    age: number;
    weight: number;
}

Create a Service

// patient-service.ts

private patientsUrl = 'api/patients';

private createPatientSubject = new Subject<IPatient>();
createPatientAction$ = this.createPatient.asObservable();

patient$ = this.http.get<IPatient[]>(this.patientsUrl)
    .pipe(
        tap(
        
    );

createPatient$ = createPatientAction$
    .pipe(
        switchMap(patientData=>this.http.post<IPatient>(this.url, patientData))
            .pipe(
                tap(data => console.log(data)),
                catchError(this.handleError)
    ));

Use on Component

// patient-component.ts

private errorMsgSubject = new Subject<string>();
errorMsg$ = this.errorMsgSubject.asObservable();

patient$ = this.patientService.patient$
    .pipe(
        catchError(err => {
            this.errorMsgSubject.next(err);
            return EMPTY;
            // return throwError(err);
        })
    );

createPatient(){
    this.api.createPatientSubject.next(this.patientFormGroup.value);
    // handle result needs finishing
}

When using Reactive Approach on Observables, one can change changeDetection Strategy to OnPush:

// patient-component.ts

@Component({
    templateUrl: './patient-list.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})

Prepare Template

// patient-list.component.html

<div *ngIf="patient$ | async as patients">
    <table>
        <tr *ngFor="let patient of patients">
            <td>{{patient.name}}</td>
            <td>{{patient.name}}</td>
        </tr>
    </table>
</div>
<div class="alert alert-danger" *ngIf="errorMsg$ | async as errorMessage">
    {{errorMessage}}
</div>

No Comments Yet.

What do you think?

Your email address will not be published. Required fields are marked *