【问题标题】:How to run an observable function in the template?如何在模板中运行可观察函数?
【发布时间】:2019-11-05 08:22:08
【问题描述】:

我有显示离线和在线用户的在线服务

 // Presence Service
 getPresence(uid: string) {
    return this.db.object(`status/${uid}`).valueChanges();
 }

在组件模板中,我可以这样运行并获得在线用户

<div *ngIf="presence$ | async as presence" 
    class="tag is-large" 
    [ngClass]="{ 'is-success':  presence.status  === 'online',
                 'is-warning': presence.status  === 'away',
                 'is-danger':  presence.status  === 'offline'
                 }"
>{{ presence.status }}</div>

但我想在模板中使用getPresence(uid: string) 函数,如下所示:

<div *ngIf="presence.getPresence('CdceTHTS5we4TRsbYE7z8bDiZbx1') | async"
    class="tag is-large" 
    [ngClass]="{ 'is-success':  presence?.status  === 'online',
                 'is-warning': presence?.status  === 'away',
                 'is-danger':  presence?.status  === 'offline'
}">dffhghhhh</div>

什么都没有发生。如何在模板中使用这个可观察函数getPresence(uid: string)

【问题讨论】:

    标签: javascript angular firebase rxjs observable


    【解决方案1】:

    您需要在您的组件上公开presence$ observable。您可以执行以下操作:

    export class MyComponent {
        presence$ = this.presenceService.getPresence("myteamId");
    
        constructor(private presenceService: PresenceService) {}
    }
    

    如果您以这种方式在组件类上公开 observable,那么您的第一个模板应该可以工作。

    【讨论】:

    • 我需要在 html 的模板中直接使用 this.presenceService.getPresence("myteamId") 。你的答案是工作。但我尝试在 html 中直接使用函数。因为我在 *ngfor 中得到了 uid
    • 如果您需要像这样使用它,请重新设计您的应用程序。您永远不知道更改检测何时运行,这会导致 *ngIf 中的语句再次被评估。我怀疑你每次都想这样做
    • 是的 finki 作为你的怀疑我每次都想这样做。感谢您的帮助
    【解决方案2】:

    您可能必须为此使用对象缓存,否则每次重新绘制组件时都会获得一个新的 observable。这样您可以继续使用函数调用,但始终获取相应的 userStatus 流

    getPresence(uid: string) {
        this.userStatus[uid]=this.usersStatus[uid]?this.usersStatus[uid]:
        this.db.object(`status/${uid}`).valueChanges();
        return this.userStatus[uid]
     }
    

    另一种选择是假设您将在组件中获取用户对象,并且您可以在传递给视图之前创建可观察的状态

    ngOnInit(){
        this.users=http.get('users').pipe(map(users=>{
           return this.users.map(user=>({...user,status:presence.getPresence(user.id)}))
        }))
    }
    

    在你看来

    <div *ngFor="let user of users | async ">
        <div *ngIf="user.status | async as presence" 
           .....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多