【问题标题】:Get string value from Observable<string> in typescript and Angular从 typescript 和 Angular 中的 Observable<string> 获取字符串值
【发布时间】:2017-08-12 16:42:32
【问题描述】:

我想从 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;
    }

上述解决方案并不总是有效。 此类问题有哪些替代解决方案?

【问题讨论】:

  • 您声明data 的方式是错误的。这不是使用异步函数的方式。

标签: angular typescript rxjs reactive-programming


【解决方案1】:

您正试图从函数getValue 返回Observable,而return responsereturn result 将不起作用,因为对http.get 的请求是异步

以下是您可以执行的一些选项:

选项 1: 在您的模板中使用 Async Pipe 订阅 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);
}

选项2: 定义不带value 字段的数组data 并稍后更新其值字段。但请注意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 的更新

对上述选项1进行了一些细微的更改,它就像魅力一样。

以下是更改:

<div *ngFor="let item of data">
  <span>{{ getValue(item.key) | async}}</span>
</div>

public getValue(key: number): any {
  return this.keyService.find(key);
}

感谢您提醒使用 Async Pipe @Pengyy(来自 OP)

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2019-02-17
    • 2014-01-24
    • 2016-08-19
    • 2019-01-30
    • 2020-12-19
    相关资源
    最近更新 更多