我想从Firebase实时数据库返回数组
这是我的密码:
add-student.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CurdService } from '../shared/curd.service';
import Swal from 'sweetalert2';
import { Student } from '../shared/student';
@Component({
selector: 'app-add-student',
templateUrl: "./regist.html",
styles: [
]
})
export class AddStudentComponent implements OnInit {
public studentForm: FormGroup;
somthing: any; somestuden: Student[];
avilableor: boolean = true;
data: any[];
some: any[];
constructor(
public crudApi: CurdService,
public fb: FormBuilder,
) {}
ngOnInit() {
this.crudApi.GetStudentsList();
this.studenForm();
this.crudApi.GetStudentsList().snapshotChanges().subscribe(data =>{
this.data = data;
})
console.log(this.data);
}
studenForm() {
this.studentForm = this.fb.group({
username: ['', [Validators.required, Validators.minLength(5)]],
fullname: [''],
email: [''],
note: [''],
});
}
get username() {
return this.studentForm.get('username');
}
get fullname() {
return this.studentForm.get('fullname');
}
get email() {
return this.studentForm.get('email');
}
get note() {
return this.studentForm.get('note');
}
ResetForm() {
this.studentForm.reset();
}
validusername(){
}
}curd.service.ts
import { Injectable } from '@angular/core';
import { Student } from './student';
import {
AngularFireDatabase,
AngularFireList,
AngularFireObject,
} from '@angular/fire/compat/database';
@Injectable({
providedIn: 'root'
})
export class CurdService {
studentsRef: AngularFireList<any>;
studentRef: AngularFireObject<any>;
constructor (private db: AngularFireDatabase){}
AddStudent(student: Student){
this.studentsRef.push({
username: student.username,
fullname: student.fullname,
email: student.email,
note: student.note,
});
}
GetSudent(id: string){
this.studentRef = this.db.object('students-list/' + id);
return this.studentsRef;
}
GetStudentsList() {
this.studentsRef = this.db.list('students-list');
return this.studentsRef;
}
UpdateStudent(student: Student) {
this.studentRef.update({
username: student.username,
fullname: student.fullname,
email: student.email,
note: student.note,
});
}
DeleteStudent(id: string) {
this.studentRef = this.db.object('students-list/' + id);
this.studentRef.remove();
}
}错误信息:
未定义
组件: is :28:12错误TypeError: this.data未定义
有人能告诉我,如何解决这个问题吗?或者有没有其他方法将数据从火基实时数据库返回到我的变量?
发布于 2022-07-08 03:07:03
您需要声明data
export class HelloComponent implements OnInit {
data = [];
....
]发布于 2022-07-08 07:23:19
在这里,您尝试的订阅是异步的。因此,如果尝试,在第28行(在回调之外)的数据值将不具有此值。因此,一旦我们收到成功回调,我们就可以尝试记录成功回调中的值。请参阅下面的片段:
ngOnInit() {
this.crudApi.GetStudentsList();
this.studenForm();
this.crudApi.GetStudentsList().snapshotChanges().subscribe(data =>{
this.data = data;
console.log(this.data); // Here we could see the value coming from service.
});
}希望这能有所帮助。
https://stackoverflow.com/questions/72906212
复制相似问题