我正在尝试从当前用户(如公司:“ ZeroMax”)获取数据,然后将此数据分配给全局变量。 并使用此变量来阐明Firebase的路径。希望您能通过研究我的代码来理解我的问题。一切正常,除了分配
this.comp = user ['company'];
这是我的drivers.service.ts文件:
export class DriversService {
user: User;
comp = '';
constructor(private db: AngularFirestore, private auth: AuthService, private afAuth: AngularFireAuth) { }
getUsers() {
return this.auth.user.pipe(
take(1),
map(user => {
// user['company'];
this.comp = user['company'];
return user['company'];
})
)
}
findUser(value) {
if (this.comp.length <= 0) {
return this.getUsers().pipe(map(user => {
this.comp = user;
console.log('Bye', this.comp);
return this.comp;
}));
}
let email = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
take(1)
);
let name = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
take(1)
);
return [email, name];
}
}
这是我的add-driver.page.ts文件:
export class AddDriverPage implements OnInit {
users = [];
participant = '';
form: FormGroup;
constructor(private driverService: DriversService, private loadingCtrl: LoadingController, private auth: AuthService) { }
ngOnInit() {
}
addDriver() {
const obs = this.driverService.findUser(this.participant);
forkJoin(obs).subscribe(res => {
if (!res || !res.length) {
return console.log('Got undefined');
}
for (let data of res) {
if (data.length > 0) {
this.users.push(data[0]);
//console.log(res);
}
console.log(res);
}
console.log('it works:', this.participant)
this.participant = '';
}, error => {
console.log('Here you got an error: ', error);
});
}
}
答案 0 :(得分:1)
访问this.comp
变量不是在位置,而是何时。到您的this.db.collection(
companies / $ {this.comp} / users``现在运行时,this.comp = user
尚未运行。
任何需要访问数据库中数据的代码都必须位于该数据可用时执行的回调中。
例如:
if (this.comp.length <= 0) {
return this.getUsers().pipe(map(user => {
let email = this.db.collection(`companies/${user}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
take(1)
);
let name = this.db.collection(`companies/${user}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
take(1)
);
return [email, name];
}));
}