繁体   English   中英

Angular - RxJS - Observable 和方法返回

[英]Angular - RxJS - Observable and method return

我的 Angular 9 应用程序中有一个方法,如下所示:

createTitleHTMLText(calendarEventObject: CalendarEventObject): string { 
this.translateService.get(calendarEventObject.calendarEventTyp).subscribe((res: string) => {
  const title = '<span><b>' + calendarEventTyp + '</b></span>;
  return title;
});

}

这个方法应该返回一个字符串,但如何做 - 要获得翻译,我需要一个 Observable 并且进一步的代码必须在 der Observable - 结果块中。 实际上我不知道该怎么做 - 有没有办法同步 Observables 或者最好的方法是什么?

目前有点不清楚。 您订阅了 HTTP 请求,但没有使用它的结果。 这里res的价值是什么? 不过我想你需要的是以下内容

createTitleHTMLText(calendarEventObject: CalendarEventObject): string { 
  this.translateService.get(calendarEventObject.calendarEventTyp).subscribe((res: string) => {
    return '<span><b>' + res + '</b></span>';
  });
}

我在这个例子中使用它:

fetchEvents(): void {
  this.events$ = this.datechoiceService.getPreparedCalendarEventsOfUser(this.user.id, this.view, this.viewDate)
 .pipe(
   map(results => {
     return results.map((calendarEventObject: CalendarEventObject) => {
      let calendarEvent: CalendarEvent<{ calendarEvent: CalendarEvent<any>; }> = {
        id: calendarEventObject.id,
        actions: this.actions,
        start: new Date(calendarEventObject.startsAt),
        end: new Date(calendarEventObject.endsAt),
        title: this.createTitleHTMLText(calendarEventObject),
        ...
      };
      return calendarEvent;
     })
   })
 );

}

您可以将 observable 转换为 promise,并且可以使用 async/await,

async createTitleHTMLText(calendarEventObject: CalendarEventObject): string {
    const calendarEventTyp = await this.translateService.get(calendarEventObject.calendarEventTyp).toPromise();
    return '<span><b>' + calendarEventTyp + '</b></span>';
}


如果我理解正确,你有一个 Observable 发出一个字符串,例如对远程服务的 http 调用,它返回(异步)一个字符串。 在您的情况下,服务是this.translateService.get(calendarEventObject.calendarEventTyp)

然后您有一个方法createTitleHTMLText(calendarEventObject: CalendarEventObject) ,它调用服务并且您希望此方法返回异步服务发出的字符串。

如果这是您想要的,您根本无法实现。 原因是服务是异步的。

您可能想要探索的是这些方面的解决方案

createTitleHTMLText(calendarEventObject: CalendarEventObject): Observable<string> { 
  this.translateService.get(calendarEventObject.calendarEventTyp).pipe(
     map((res:   string) =>. '<span><b>' + calendarEventTyp + '</b></span>')
  )
}

在这个版本中, createTitleHTMLText函数向感兴趣的人返回一个 Observable。 这样的 Observable 实际上可以在需要的地方订阅,也许可以使用 Angular async模板管道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM