如何将 observable 中的值传递给 Angular2 中的(单击)处理程序 [英] How to pass a value inside an observable to (click) handler in 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!?
推荐答案
对于向任何东西添加点击处理程序的一般情况,而不仅仅是 ,您可以使用隐藏的
元素来保存 promise/observable 流的最新值,然后从其他元素访问该值.
For the general case of adding a click handler to anything, not just a <button>
, you can use a hidden <input>
element to hold the latest value of the promise/observable stream, and then access that value from other elements.
<input #dummy style="display: none" type="text" value="{{ myAsyncSource | async }}">
<a (click)="myFunction(dummy.value)">{{ dummy.value }}</a>
这篇关于如何将 observable 中的值传递给 Angular2 中的(单击)处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!