如何将 observable 中的值传递给 Angular2 中的(单击)处理程序 [英] How to pass a value inside an observable to (click) handler in Angular2

查看:22
本文介绍了如何将 observable 中的值传递给 Angular2 中的(单击)处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 Angular 2 学习 observable 编程,但我没有得到一个重要的点 - 如何在模板级别的 (click) 事件中传递 observable 中的值(不订阅 observable 中的TS 文件,并将可观察值转换为成员变量).

I try to learn observable programming with Angular 2 BUT I don't get one important point - how to pass in the value that is in an observable in the (click) event in the template level (without subscribing the observable in the TS file and turn the observable value into member variable).

正如许多 Firebase 专家所建议的那样只要有可能,尝试在 angular2 中使用 | async 并防止手动订阅!"- 不想手动订阅 task$ 并将其转换为数组的原因.

As lots of Firebase experts suggest this "Wherever possible, try to use | async in angular2 and prevent manual subscriptions!" - reason for not wanting to manually subscribe to task$ and turn it into an array.

例如:

我在组件的 TS 文件中有这个:

I have this in my TS file of component:

task$: Observable<Task>;

this.task$ = this.tasksService.findTaskById(taskId);

在我的服务中,这是使用 AngularFire 调用 firebase 的代码,它返回一个 observable:

In my service, this is the code to call firebase with AngularFire which return an observable:

import {Task} from "../model/task";
constructor(private db:AngularFireDatabase, @Inject(FirebaseRef) fb) {
   this.sdkDb = fb.database().ref();
}

findTaskById(id:string):Observable<Task> {

  return this.db.object('tasks/' + id).map(task => Task.fromJson(task));

}

在我的模板中,我可以像这样使用异步管道在 Angular2 中毫无问题地使用该值:

In my template, I can use the value without problem in Angular2 with async pipe like so:

<md-card-title>{{(task$ | async)?.title}}</md-card-title>

但是我有一个按钮需要这个 task$ 中的 $id 值,如下所示:

But then I have a button that need the $id value inside this task$ like so:

<button md-button *ngIf="(authInfo$ | async)?.isLoggedIn()" (click)="deleteTask((task$ | async)?.$key)">Delete</button>

这将不起作用,因为单击不允许在表达式中使用管道......而且我不想订阅 task$ 并将其转换为成员变量(最佳做法是将 task$ 保留为可观察风格的 RXJS 编程?!)

This won't work as click does not allow pipe inside the expression... And I DO NOT want to subscribe to task$ and turn it into member variable (best practises to keep it task$ for obserable style RXJS programming?!)

那么我如何获得 $key 值,因为它最初不存在并且我不能使用异步管道!?

So how do I get the $key value as it is not there initially and I can not use async pipe!?

推荐答案

对于向任何东西添加点击处理程序的一般情况,而不仅仅是

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆