0

I would like to change my code towards a Reactive style, however I am struggling with the syntax when attempting to pass through parameters within the async pipe to an Observable.

My current working code that is not Reactive (stydent.component.ts):

deleteStudent(id: number) {
  this.uniCrudService.deleteStudent(id)
  .subscribe( res => {
    console.log(`deleteStudent: ${JSON.stringify(res)}`);
    this.getStudents();
  });
}

In my student.component.html template I am calling the deleteStudent like:

<a routerLink="" (click)="deleteStudent(student.id)">Delete</a>

The problem is that I need to use the async pipe on an observable function that receives a parameter (for a Reactive style?).

For example:

deleteStudent(id: number): Observable<Student> {
return this.deleteStudent$ = this.uniCrudService.deleteStudent(id)
  .pipe( tap (res => {
    console.log(`deleteStudent: ${JSON.stringify(res)}`);
    this.getStudents();
  }));

and in the template:

<a routerLink="" (click)="deleteStudent(student.id) | async">Delete</a>

However this throws the error: Cannot have a pipe in an action expression. Looking at this answer I am understanding that I cannot make this piece of my code Reactive, and I will be forced to keep the unwanted subscription. Is this the case? How do I make my deleteStudent Reactive and get rid of the subscription?

Luke
  • 776
  • 9
  • 24

1 Answers1

1

I think you have a design issue there. The deleteStudent(id: number) is an event handler, so it should not return any values or have any subscribers. Your initial code is correct.

If you want a more "reactive" approach you could create a Subject:

public students$: Subject<any>;

constructor(){ 
   this.students$ = new Subject<any>();
}

ngOnInit() {
   this.students$.subscribe(() => { 
      // do something with students
   });
}

deleteStudent(id: number) {
 this.uniCrudService.deleteStudent(id)
 .subscribe( res => {
   console.log(`deleteStudent: ${JSON.stringify(res)}`);
   this.students$.next();
 });
Lucian Moldovan
  • 567
  • 5
  • 6