从方法返回数组<custom class =“”>

时间:2017-02-12 03:52:58

标签: angular angularfire2

好的,所以我打电话给firebase并返回给定位置的孩子。

然后我遍历返回的值并填充我的自定义类,即descriptionid这是有效的,因为我将options记录到控制台,我可以看到条目。

问题我试图将此方法中的值返回到我的组件,因为代码如下所示:

 getIntent(): Promise<Array<Dropdown>> {

    const options: Dropdown[] = [];
    var d = this.af.database.list('/option1').subscribe(items => {
        items.forEach(item => {
            options.push({
                id: item.$key,
                description: item.$value
            })
            return false;
        });
    });

    return options;

}

在返回行上,当前带有以下错误的下划线:

Type 'Dropdown[]' is not assignable to type 'Promise<Dropdown[]>'. Property '[Symbol.toStringTag]' is missing in type 'Dropdown[]'.

我试过了:

return options as Promise<Array<Dropdown>>;

但遗憾的是,这没有用,有人可以说明如何让这个函数返回下拉选项。

旁注:目前也在使用angularfire2

1 个答案:

答案 0 :(得分:1)

import 'rxjs/add/operator/map';

getIntent(): Observable<Dropdown[]> {

  return this.af.database.list('/option1')
    .map(items => items
      .map(({$key, $value}) => ({
        id: $key,
        description: $value
      })
    );

}

然后,您将在某个组件中订阅此方法。

值得注意的是,虽然您的问题建议使用名为class的{​​{1}},但我们并没有实例化它。如果Dropdown确实被声明为Dropdown,则最好将其更改为class,以便无法意外执行始终interface的检查是假的。

<强>前

instanceof

<强>后

export class Dropdown {
  id: string; // maybe number?
  description: string;
}
相关问题