使用异步管道到模板上的属性 [英] using async pipe to the property on template

查看:53
本文介绍了使用异步管道到模板上的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

export class MyClass {
    data: MyData;  
    constructor(private dataService: DataService) {    
      this.dataService.getData().subscribe((myData) => {
        this.data = myData;
      });  
    }
}

通过Web服务成功检索到

数据.MyData对象具有属性firstName,我想使用异步管道在模板内部表示该属性.

data is successfully retrieved trough web service. MyData object has property firstName which I want to represent inside template using async pipe.

我尝试过

<input required [ngModel]="data.firstName | async" (ngModelChange)="onChange($event)" name="firstName">

这种方法根本不将属性绑定到模板, [(ngModel)] ="data.firstName" 可以,但是我被告知该方法不能与异步方法一起使用管道.

this approach doesn't bind property to the template at all, [(ngModel)]="data.firstName" works but I've been told that this approach cannot be used together with async pipe.

更新:

getData(): Observable<MyData>{
        return Observable.from([this.fakeData()]
            .map(res=>res as MyData));
    }

推荐答案

可以使用

export class MyClass {
    data: Promise;  
    constructor(private dataService: DataService) {    
      this.data = this.dataService.getData()
    }
}

|异步管道已经在订阅

<input required [ngModel]="(data | async)?.firstName" (ngModelChange)="onChange($event)" name="firstName">

或带有您的代码

<input required [ngModel]="data?.firstName" (ngModelChange)="onChange($event)" name="firstName">

我刚刚在其中添加?的地方是为了避免在数据不可用时出现错误.

where I just added ? to avoid an error while the data is not yet available.

这篇关于使用异步管道到模板上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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