具有参数化异步管道的反应式模板

时间:2018-10-31 09:31:05

标签: angular asynchronous ngrx

我想将代码更改为Reactive样式,但是当尝试将异步管道中的参数传递给Observable时,我在语法上苦苦挣扎。

我当前未激活的工作代码(stydent.component.ts)

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

在我的student.component.html模板中,我像这样呼叫deleteStudent

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

问题是我需要在可观察函数中使用async管道来接收参数(用于响应式样式?)。

例如:

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

并在模板中:

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

但这会引发错误:Cannot have a pipe in an action expression。看this answer时,我了解到我无法使这段代码处于活动状态,因此我将不得不保留不需要的subscription。是这样吗如何使我的deleteStudent处于活动状态并摆脱subscription

1 个答案:

答案 0 :(得分:1)

我认为您那里有一个设计问题。 deleteStudent(id: number)是事件处理程序,因此它不应返回任何值或具有任何订阅者。您的初始代码是正确的。

如果您想要一种更“主动”的方法,可以创建一个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();
 });
相关问题