代码之家  ›  专栏  ›  技术社区  ›  virsha

从typescript和Angular中的Observable<string>中获取字符串值

  •  4
  • virsha  · 技术社区  · 9 年前

    我想从Observable中获取字符串值,并将值从函数返回给调用方函数。

    我有一个键数组,我想一个接一个地获取所有键的值(字符串),并显示它的html组件,它有菜单栏。

    以下是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组件中的所有值。

    解决方案之一是:

    private getValue(key: number): string {
            let result: string;
            this.keyService.find(key).subscribe(res => result = res);
            return result;
        }
    

    上述解决方案并不总是有效。

    1 回复  |  直到 9 年前
        1
  •  14
  •   Pengyy    9 年前

    你想回来 Observable from函数 getValue return response 或 return result 无法工作,因为请求 http.get 是 异步 .

    以下是您可以做的一些选择:

    异步管道 在您的模板上订阅的结果 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: 定义阵列 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);
    }
    

    异步管道 @彭YY(来自OP)