映射到 FirebaseListObservable<any[]> 时出现类型错误
Type error when mapping over FirebaseListObservable<any[]>
我正在从 Firebase 获取一个集合并尝试映射该集合,返回对象实例。我的代码如下所示:
class Todo {
constructor(public text: string) { }
}
this.db.list('todos').map(todo => {
return new Todo(todo);
});
这确实有效,但我在 new Todo(todo)
行收到 TypeScript 智能感知错误,内容为:
Argument of type 'any[]' is not assignable to parameter of type 'string'.
我可以看到 this.db.list
returns 是 FirebaseListObservable<any[]>
的一种。但是,当我调试此行并获取 todo
的类型时,它报告它是一个字符串而不是任何类型的数组。
我不太确定如何让 TypeScript 在这里变得快乐。
更新
结果证明这是我的一个错误。我在测试中错误地模拟了 Firebase 的可观察响应,并且以错误的方式查看结果。 Cartant 的回答帮助我看到了这一点。
由 list
编辑的可观察对象 return 将发出一组待办事项;没有一个待办事项。也就是说,它将发出 any[]
并且发出的数组中的每个元素将对应于 todos
.
下的一个键
如果 todos
下的键有字符串值,AngularFire2 应该发出一个包装值数组,像这样:
[{
$value: '<value1>',
$key: '<key1>'
}, {
$value: '<value2>',
$key: '<key2>'
}]
您可能想使用 Array.prototype.map
到 return 待办事项数组:
this.db
.list('todos')
.map((todos: any[]) => todos.map((todo: any) => new Todo(todo.$value));
我正在从 Firebase 获取一个集合并尝试映射该集合,返回对象实例。我的代码如下所示:
class Todo {
constructor(public text: string) { }
}
this.db.list('todos').map(todo => {
return new Todo(todo);
});
这确实有效,但我在 new Todo(todo)
行收到 TypeScript 智能感知错误,内容为:
Argument of type 'any[]' is not assignable to parameter of type 'string'.
我可以看到 this.db.list
returns 是 FirebaseListObservable<any[]>
的一种。但是,当我调试此行并获取 todo
的类型时,它报告它是一个字符串而不是任何类型的数组。
我不太确定如何让 TypeScript 在这里变得快乐。
更新
结果证明这是我的一个错误。我在测试中错误地模拟了 Firebase 的可观察响应,并且以错误的方式查看结果。 Cartant 的回答帮助我看到了这一点。
由 list
编辑的可观察对象 return 将发出一组待办事项;没有一个待办事项。也就是说,它将发出 any[]
并且发出的数组中的每个元素将对应于 todos
.
如果 todos
下的键有字符串值,AngularFire2 应该发出一个包装值数组,像这样:
[{
$value: '<value1>',
$key: '<key1>'
}, {
$value: '<value2>',
$key: '<key2>'
}]
您可能想使用 Array.prototype.map
到 return 待办事项数组:
this.db
.list('todos')
.map((todos: any[]) => todos.map((todo: any) => new Todo(todo.$value));