How to pass a value inside an observable to (click) handler in Angular2

我怕爱的太早我们不能终老 提交于 2020-01-02 07:06:01

问题


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).

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.

For example:

I have this in my TS file of component:

task$: Observable<Task>;

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

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));

}

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>

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>

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?!)

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


回答1:


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>



回答2:


The way I solved the issue is that i created a variable for the button and passed its value to the handler. Also the Observable is bound to value property.

 <button type="button" #item value="{{i$ | async}}"  (click)="buttonClicked(item.value)">BUTTON</button>


来源:https://stackoverflow.com/questions/41730811/how-to-pass-a-value-inside-an-observable-to-click-handler-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!