我试图使用lodash和angularfire2遍历用户数据数组但是我得到错误TypeError:无法读取属性' db'未定义的
典型的推送阵列 [ 0:user1, 1:user2, 2:user3, ]
import { AngularFireDatabase} from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';;
import * as _ from 'lodash';
constructor(
private db : AngularFireDatabase,
private afAuth : AngularFireAuth) {}
addGroupChats(allGroupMember) {
console.log("allGroupMember", allGroupMember);
//this line work well without error
console.log("value[0]", allGroupMember.users[0]);
//let endpoint = this.db.object(`/users/${allGroupMember.users[0]}/groups/${allGroupMember.groupUid}`);
//endpoint.set(true);
this line throws ERROR TypeError: Cannot read property 'db' of undefined
_.forEach(allGroupMember.users, function(value) {
let endpoint = this.db.object(`/users/${value}/groups/${allGroupMember.groupUid}`);
endpoint.set(true);
});
}
答案 0 :(得分:1)
您需要使用arrow functions进行回调。
this
引用函数对象而不是您的案例中的类。
这里:
_.forEach(allGroupMember.users,(value) => {
let endpoint = this.db.object(`/users/${value}/groups/${allGroupMember.groupUid}`);
endpoint.set(true);
})