我想从 Observable 获取字符串值并将该值从函数返回给调用者函数。
例如:
我有一组键,想一一获取所有键的值(字符串)并将其显示在具有菜单栏的 html 组件中。
这是 ts 文件:
key-list.component.ts
public data = [ { 'key': 1, 'value' : this.getValue(1)},
{ 'key': 2, 'value' : this.getValue(2)},
...
];
private getValue(key: number): string {
return this.keyService.find(key).subscribe(response => {
return response;
});
}
keyService.ts
...
public find(key:number): Observable<any> {
return this.http.get(`/api/keys/${key}`).map(res => res.json() || {});
}
...
我想显示 html 组件中的所有值。
但在 key-list.component.ts 中出现错误,可观察到字符串类型。
我如何解决这个订阅方法并确保 getValue 应始终返回字符串,并使其完美无缺。
解决方案之一是:
private getValue(key: number): string {
let result: string;
this.keyService.find(key).subscribe(res => result = res);
return result;
}
上述解决方案并不总是有效。
此类问题有哪些替代解决方案?
你正在尝试返回Observable
从函数getValue
, and return response
or return result
不起作用,因为请求http.get
is 异步.
以下是您可以执行的一些选项:
Option1: using 异步管道在您的模板中订阅以下结果http.get
并从函数中删除订阅部分getValue
.
<div *ngFor="let item of data">
<span>{{item.value | async}}</span>
</div>
// return Observable and subscribe by async pipe at template
private getValue(key: number): string {
return this.keyService.find(key);
}
Option2:定义数组data
没有value
字段并稍后更新其值字段。但要小心的是value
场将是undefined
除非你得到回复this.keyService.find(key)
.
public data = [
{ 'key': 1},
{ 'key': 2},
...
];
constructor() {
this.data.forEach(item => {
this.keyService.find(item.key).subscribe(response => {
item.value = response; // update value field here.
});
});
}
// here getValue function is no longer necessary.
希望这会有所帮助。
来自OP的更新
通过对上述选项进行一些细微的更改,它的效果就像魅力一样。
以下是变化:
<div *ngFor="let item of data">
<span>{{ getValue(item.key) | async}}</span>
</div>
public getValue(key: number): any {
return this.keyService.find(key);
}
感谢提醒使用异步管道@Pengyy(来自OP)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)