Javascript 无法更新firebase数据
组件.tsJavascript 无法更新firebase数据,javascript,angular,typescript,firebase-realtime-database,angularfire,Javascript,Angular,Typescript,Firebase Realtime Database,Angularfire,组件.ts export class HomeComponent { home= { name: '', age: null, mobileNo: null, area: '', address: '', test: '' } as home; id; constructor(private homeService: HomeService ,private router: Router , public authService: AuthService,
export class HomeComponent {
home= {
name: '',
age: null,
mobileNo: null,
area: '',
address: '',
test: '' } as home;
id;
constructor(private homeService: HomeService ,private router: Router , public authService: AuthService,
public ngZone: NgZone, private route: ActivatedRoute, private db: AngularFireDatabase) {
this.id = this.route.snapshot.paramMap.get('id');
if (this.id) this.homeService.get(this.id).valueChanges().pipe(take(1))
.subscribe((h) => (this.home = h as home));
}
save(home){
console.log(home)
console.log(this.id) // returns null
if(this.id) this.homeService.update(home, this.id) //update if user exist
else this.homeService.create(home) // create if user exist
}
}
服务.ts
export class HomeService {
constructor( private db: AngularFireDatabase ) { }
create(home){
return this.db.list('/home/').push(home);
}
update(home, homeId) {
return this.db.object('/home/' + homeId).update(home);
}
get(homeId) {
return this.db.object('/products/' + homeId);
}
}
如果用户登录,我会尝试更新用户详细信息,但不是更新,而是创建一个具有新id的新对象
如果您使用同一url从一个页面多次更新
home
,它是否会添加多个新集合?是的,如果用户再次登录,我想更新是否有任何方法可以将数据映射到用户,这样每当用户登录时,您遇到的问题可能是因为您使用用户ID获取对象,但是,在使用push()
创建对象时,会给该对象一个随机id,因此存在不匹配。我不知道update()。如果是这样,更新将在第二次开始工作。但是,您对我前面评论的回答表明,情况可能并非如此。update()不创建任何对象,而是更新提交的对象。我试图传递用户对象,但它抛出了一个错误,即用户中不存在这些详细信息(mobileNo、Area等)。如果您使用同一url从一个页面多次更新home
,它是否会添加多个新集合?是的,如果用户再次登录,我想更新。是否有任何方法可以将数据映射到用户,因此,每当用户登录时,它都会被更新。您遇到的问题可能是因为您使用用户id获取对象,但在使用push()
创建对象时,对象会被随机分配一个id,因此存在不匹配。我不知道update()。如果是这样,更新将在第二次开始工作。但是,您对我前面评论的回答表明,情况可能并非如此。update()不创建任何对象,而是更新提交的对象。我试图传递用户对象,但它抛出了一个错误,即这些详细信息(mobileNo、Area等)在用户中不存在