我是新手。请帮助我从Firestore获取单个数据。我正在从数据库中获取全部数据,但是我需要数据库中的特定数据。 这是我获取全部数据的角度代码。我已经提到了两个代码文件,一个是服务文件,另一个是显示代码文件。
service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore,AngularFirestoreDocument,AngularFirestoreCollection } from '@angular/fire/firestore';
import { User } from '../models/user';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class RegisterService {
private registerCollection : AngularFirestoreCollection<User>;
private resgisters : Observable<User[]>;
private registerDocu : AngularFirestoreDocument<User>;
constructor(public db : AngularFirestore) {
this.registerCollection = db.collection<User>('Register');
this.resgisters = db.collection('Register').valueChanges();
this.resgisters = this.registerCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
addRegister(user: User) {
this.registerCollection.add(user);
}
getRegister(){
return this.resgisters;
}
}
Profile.page.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { LoggingService } from '../../../services/logging.service';
import { RegisterService } from '../../../services/register.service';
import { User } from '../../../models/user';
import * as firebase from 'firebase/app';
@Component({
selector: 'app-profile',
templateUrl: './profile.page.html',
styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
user : User[];
constructor(private registerservice : RegisterService,private loggingService: LoggingService, private activatedRoute: ActivatedRoute, private authService: AuthService) { }
ngOnInit() {
this.registerservice.getRegister().subscribe(register => {
this.user = register;
console.log(this.user);
});
}
}
答案 0 :(得分:1)
为了从Firestore数据库中获取单个对象,您需要查询文档。根据您的代码结构,getRegister()方法应为:
getRegister(node) {
return this.db.Doc<User>('Register/' + node).valueChanges();
}
您可以在库github页面上找到文档:https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md