【问题标题】:Observable inside Ngfor可在 Ngfor 内部观察到
【发布时间】:2019-10-28 14:20:39
【问题描述】:

我正在学习编程...

我正在使用 angularfire2 (firebase) 创建某种论坛。我有 2 项服务,一个管理所有用户配置文件数据,另一个管理消息。使用 *ngfor 我显示所有消息(调用组件中的服务功能)。消息接口有提交消息的用户的uid。有了这个 uid,我想获取用户个人资料图片,例如显示在消息中。

问题是,当我调用函数时,我在一个可观察对象中得到了一个可观察对象,并且我的应用程序启动了一个 bucle。我做错了什么?

谢谢!

admin.requests.component.html 。

    <div *ngFor="let request of requests" class="card shadow">



    ..img  ... src="{{getUserProfilePicture(request.clientId)}}" ... ">

getUserProfilePicture(uid) 返回 uid = clientId 的 DOC 的 imgURL 的值

【问题讨论】:

  • 你是说requests 是一个可观察的数组吗?还是 getUserProfilePicture 返回一个 observable?
  • 我的意思是 getUserProfilePicture 返回一个 observable。谢谢

标签: angular firebase


【解决方案1】:

您正在寻找async pipe

异步管道订阅 Observable 或 Promise 并返回 它发出的最新值。当发出一个新值时,异步 管道标记要检查更改的组件。当组件 被破坏,异步管道自动取消订阅以避免 潜在的内存泄漏。

因此,如果您的 observable 返回带有图像 src 的字符串,则重构后的代码可能如下所示:

    ..img  ... src="{{getUserProfilePicture(request.clientId) | async}}" ... ">

我在ngFor 循环中创建了一个working example of the async pipe 以供参考。

使用异步管道需要注意一些潜在的事情:每次使用同一个 observable 时,它​​都会再次订阅 observable,除非您使用 as 语法捕获该值。这意味着:如果您有一个调用 Web 服务的异步管道,例如,如果您执行以下操作,它将被多次调用:

<!-- Async pipe subscribes once... -->
<img src="{{someHttpCall(request.clientId) | async}}"/>
<!-- Async pipe subscribes again... -->
<p>Img loaded from: {{someHttpCall(request.clientId) | async}}</p>

如果您想为我们重构上面的 as 语法以捕获输出并避免多次服务器调用,它看起来像这样:

<!-- Capture our observable to prevent subsequent subscriptions. 
     Async pipe only subscribes once. -->
<ng-container *ngIf="someHttpCall(request.clientId) | async as imgSrc">
   <img src="{{ imgSrc }}"/>
   <!-- Also note we don't need the async pipe because it already subscribed 
        to the observable for us and we captured the value in our template -->
   <p>Img loaded from: {{ imgSrc }}</p>
</ng-container>

无论如何,这是许多新 Angular 开发人员陷入的一个陷阱,所以我想我不会在没有至少一点警告的情况下引入 async 管道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 2021-11-13
    • 2018-06-23
    • 1970-01-01
    • 2017-06-17
    • 2020-12-12
    • 2019-12-28
    • 1970-01-01
    相关资源
    最近更新 更多