不能分配给类型为

不能分配给类型为

本文介绍了类型为“(snap:DataSnapshot)=>”的参数void'不能分配给类型为'(a:DataSnapshot)=>的参数。布尔”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于这个问题的几个问题和答案,但是无法解决它。



我使用Ionic2,我有一个方法从Firebase数据库v3中检索数据。
我不明白为什么我会在控制台出现错误信息,当我执行 ionic serve 时:

 错误TS2345:类型'(snap:DataSnapshot)=> void'不能分配给类型为'(a:DataSnapshot)=>的参数。布尔。 
键入'void'不可分配为键入'boolean'。

这是方法:

<$ p $ orderByChild(id)。on(value,this);} $ {code>}构造函数(private http:Http){

firebase.database函数(快照){
let items = [];
snapshot.forEach(snap => {
items.push({
uid:snap.val()。uid ,
username:snap.val()。username,
});
});
});


$ / code $ / pre

解决方案

forEach 方法在 DataSnapshot 中有以下签名:

<$ p forEach(action:(a:firebase.database.DataSnapshot)=> boolean):boolean;

作为动作可以返回 true 使枚举短路并提前返回。如果返回一个虚假值,枚举继续正常。 (这在中有提及。) false (继续枚举子快照):

/ b>

 数据库()
.ref(users)
.orderByChild(id)$ b ($ snap)=> {
items.push({
uid:snap.val()。uid,
username:snap.val()。username
});
return false;
});
});


I've already read several questions and answers about this problem but wasn't able to solve it.

I'm using Ionic2 and I have a method which retrieves data from Firebase Database v3.I don't understand why I get following error in console when I do ionic serve:

Error TS2345: Argument of type '(snap: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'.
  Type 'void' is not assignable to type 'boolean'.

This is the method:

constructor(private http: Http) {

    firebase.database().ref('users').orderByChild("id").on("value", function(snapshot){
                    let items = [];
                    snapshot.forEach(snap => {
                        items.push({
                            uid: snap.val().uid,
                            username: snap.val().username,
                        });
                    });
                });
            }
}
解决方案

The forEach method in the DataSnapshot has this signature:

forEach(action: (a: firebase.database.DataSnapshot) => boolean): boolean;

as the action can return true to short-circuit the enumeration and return early. If a falsy value is returned, enumeration continues normally. (This is mentioned in the documentation.)

To appease the TypeScript compiler, the simplest solution would be to return false (to continue enumerating the child snapshots):

database()
    .ref("users")
    .orderByChild("id")
    .on("value", (snapshot) => {
        let items = [];
        snapshot.forEach((snap) => {
            items.push({
                uid: snap.val().uid,
                username: snap.val().username
            });
            return false;
        });
    });

这篇关于类型为“(snap:DataSnapshot)=&gt;”的参数void'不能分配给类型为'(a:DataSnapshot)=&gt;的参数。布尔”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:33