observable 准备好后如何调用函数

问题描述

我是 Angular 和 Observables 的新手。我的问题是: 在我的组件 HomePage 中,我调用调用 http.get 并返回一个可观察的服务。在我的模板主页上,我对此数据 $ 使用异步。我需要在 ngOnInit 中调用一个 void 函数,该函数将在返回时使用 data$。所以我无法弄清楚如何做到这一点。

HomePage.ts

export class HomePage implements OnInit {

  data$: Observable<any>;

  ngOnInit(): void {
    //I need userId that will be returned here
    this.data$ = this.dataService.getMyData(); 
    //how to call this function after data$ is returned?
    this.sendMessage(data.userId);
  }

  sendMessage(data.userId){
     //send this userId 
  }
}

主页.html

<app-homepage form="true" *ngIf="{ data: data$ | async} as myData">
<div *ngIf="data.userId">
///....

我试过了:但是每次我在页面上输入一些数据时 - 它都会多次调用 sendMessage()...

this.data$ = this.dataService.getMyData().pipe(
      tap((data) => {
        this.sendMessage(data.userId);
        console.log("in pipe")//here I see multiple calls when I click on checkBox for exemple..
      }));

解决方法

如果您的服务返回 Observable,那么您需要 subscribe 以读取响应内容,如下所示:

export class HomePage implements OnInit {

  // data$: Observable<any>;
  theResult: any;

  ngOnInit(): void {    
    this.dataService.getMyData().subscribe((response) => {
      console.log('See your response',response);
      theResult = response.userId;
      this.sendMessage(theResult);
    });
  }

  sendMessage(data.userId){
     //send this userId 
  }
}

请记住,当您对 Observable 进行 subscribe 操作时,这是一个 asynchronous 操作,这就是为什么在 response 步骤中获得 subscribe 之后,您将需要调用其他函数。

,

试试

this.data$ = this.dataService.getMyData().pipe(
  take(1),tap((data) => {
    this.sendMessage(data.userId);
    console.log("in pipe")//here I see multiple calls when I click on checkbox for exemple..  
  }
));
,

当值通过流发出时,使用 tap 运算符是运行副作用的合适方法。

如果您想防止多个订阅触发副作用逻辑,您可以使用 shareReplay 运算符来防止这种行为:

this.data$ = this.dataService.getMyData().pipe(
    tap(data => this.sendMessage(data.userId)),shareReplay()
);

这是一个 StackBlitz 示例

每次我在页面上输入一些数据时 - 它多次调用 sendMessage()

如果与页面交互导致调用被多次执行,则更改检测可能会以某种方式导致这种情况。您可能需要共享更多代码才能弄清楚为什么会这样。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...