组件 ngOninit 模型绑定问题
组件 profile.component.ts
是一个子组件,正在尝试绑定一个虚拟模型,如下所示。
export class ProfileComponent implements OnInit {
constructor() {
}
objName: any;
ngOnInit() {
this.getAsyncData().subscribe(j => {
this.objName = j.FirstName;
});
}
getAsyncData() {
// Fake Slow Async Data
return of({
FirstName: 'Luke',
LastName: 'Skywalker'
}).pipe(delay(2000));
}
}
下面是我的 HTML 页面。
<div class="col-12 col-form-label mb-5">
{{objName | async}}
</div>
现在,无论我是否在 HTML 页面上使用 async,这个 this.objName = j.FirstName;
都会获取数据,但不会绑定在 HTML 页面上。
Component profile.component.ts
is a child component and is trying to bind a dummy model which is shown below.
export class ProfileComponent implements OnInit {
constructor() {
}
objName: any;
ngOnInit() {
this.getAsyncData().subscribe(j => {
this.objName = j.FirstName;
});
}
getAsyncData() {
// Fake Slow Async Data
return of({
FirstName: 'Luke',
LastName: 'Skywalker'
}).pipe(delay(2000));
}
}
Here is my HTML page below.
<div class="col-12 col-form-label mb-5">
{{objName | async}}
</div>
Now this this.objName = j.FirstName;
gets data but does not bind on HTML page whether I use async or not on HTML page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想使用
| async
管道它只能在 Observable 上工作。在您的情况下,
this.objName
不是可观察的。this.objName
是发出的对象j
上的属性Firstname
的值。您试图将单个值视为可观察的值 - 这不是它的工作原理。按照我的例子可以更好地理解这一点。命名属性时也尝试使用驼峰命名法而不是帕斯卡命名法(例如,将
FirstName
改为firstName
)。工作示例: https:// /stackblitz.com/edit/async-pipe-8c2brn?file=app%2Fasync-pipe%2Fasync-pipe.component.ts
If you want to use the
| async
pipe it will only work on an Observable.In your case
this.objName
is not an observable.this.objName
is a value from propertyFirstname
on objectj
which was emitted. You are trying to treat a single value as an observable - that's not how this works. Follow my example for better understanding on this.Also try to use camelCase instead of PascalCase when naming properties (e.g
FirstName
tofirstName
).Working example: https://stackblitz.com/edit/async-pipe-8c2brn?file=app%2Fasync-pipe%2Fasync-pipe.component.ts