【问题标题】:from Firebase database retrieve details against a particular value using angular从 Firebase 数据库使用角度检索特定值的详细信息
【发布时间】:2020-08-05 22:50:56
【问题描述】:

在我的演示应用程序中,我有一个“员工”界面,其中包含以下字段: employee.ts

export interface Employee{
    id:string;
    firstName:string;
    lastName:string;
    email:string;
    mobileNumber:string;

}

在 UI 中,我显示了添加到 Firebase 数据库中的所有员工。 现在,我想使用员工 ID 更新该员工的特定数据。 edit-employee.component.ts

import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-edit-employee',
  templateUrl: './edit-employee.component.html',
  styleUrls: ['./edit-employee.component.css']
})
export class EditEmployeeComponent implements OnInit {
employee:Employee;
id:string;
submitted:boolean=false;
  constructor(private employeeService:EmployeeService,
    private activeRoute:ActivatedRoute) { }

  ngOnInit(): void {
    this.activeRoute.params.subscribe(
    (data)=>{
       this.id=data['id'] 
    }
    );
    console.log('id::'+this.id);
    this.employeeService.getEmployeeById(this.id).subscribe(
      (data)=>{
        console.log(data);
        this.employee=data.map((e)=>{
            return{
              firstName:e.payload.doc.data()['firstName'],
              lastName: e.payload.doc.data()['lastName']
            }
        })
        console.log(this.employee);
      }
    )
  }
  onSubmit(){
    console.log('submitted');
    this.submitted=true;
  }

}

employee.service.ts:

getEmployeeById(id:string):Observable<any>{
   //return this.firestore.collection('users').doc(id).valueChanges();
   return this.firestore.doc('users/'+id).get();
  }

我想根据从 UI 中选择的员工 ID 填充数据。 但是我在填充这些数据时遇到错误。

【问题讨论】:

  • console.log(data)中的数据类型是什么; ? .. 当然,它不是一个数组,data.map() 失败了。
  • 我是否需要为 getEmployeeById() 方法更改服务类中的任何内容。 getEmployeeById(id:string):Observable{ //return this.firestore.collection('users').doc(id).valueChanges();返回 this.firestore.doc('users/'+id).snapshotChanges(); }

标签: angular firebase-realtime-database


【解决方案1】:

考虑 id 是存储在 Firestore 中的对象的文档 ID。这将返回一个对象。

return this.firestore.doc('users/'+id).valueChanges();

否则,如果它是保存对象的属性,那么你必须在集合中查询。这将返回一个对象数组。只有 1,如果 id 是唯一的

return this.firestore.collection('users', ref => ref.where('id', '==', id)).valueChanges();

在订阅中记录这些数据。它应该是您可能保存在 Firestore 中的确切对象。

ngOnInit(): void {
  this.activeRoute.params.subscribe(
    (data)=>{
      this.id = data['id'] 
      console.log('id::'+this.id);
      this.employeeService.getEmployeeById(this.id).subscribe(
       (data)=>{
         console.log(data); // Should be the exact same object that was saved.
         // Using the 2nd way, this will return an array with 1 item. So take the 0th element, ie data[0]
         this.employee = data; // data[0]
      });
    }
  );
}

注意:始终维护类型以获得 TypeScript 的好处。

【讨论】:

  • ,如果我点击第二条记录的更新按钮,这仅适用于第一次点击,它仍然显示第一条记录。任何线索
  • 您需要提供更多代码,才能知道错误在哪里。一个疯狂的猜测是让你看看你在哪里调用 getEmployeeByID()。如果您注意到,我已将其移到 params.subscribe() 调用中,而您的原始调用将其移到了外部。
  • 对不起,我做错了。它现在正在工作。非常感谢。
【解决方案2】:

这里的主要问题是您假设 this.id 在您调用 this.employeeService.getEmployeeById(this.id) 时被分配了一个值。但是this.id 是异步分配的。尽管有时可能会正确分配,但不能保证每次都正确分配。在这种情况下,您可以使用 RxJS 高阶映射运算符之一,例如 switchMap

ngOnInit(): void {
  this.activeRoute.params.pipe(
    switchMap(data => {
      this.id = data['id'];
      console.log('id::'+this.id);
      return this.employeeService.getEmployeeById(this.id);
    })
  ).subscribe(
    data => {
      console.log(data);
      this.employee = data.map((e) => ({
        firstName:e.payload.doc.data()['firstName'],
        lastName: e.payload.doc.data()['lastName']
      }))
      console.log(this.employee);
    }
  );
}

这可能无法解决您的问题。为此,您需要确保订阅中的 data 是一个数组。如果没有,则不能在其上调用map 函数。

【讨论】:

  • 在与该 id 对应的 fire base db 记录中存储为键/值对,我只想检索这些记录。如何从我的服务调用中将其作为数组传递?任何想法都会有所帮助。
  • @stumbler:您在订阅中执行console.log(data)。请显示它的输出以清楚地了解您的数据结构。
  • 当然。已编辑。请检查
  • 似乎响应是一个对象,它不包含您所指的doc 属性。您需要再次检查如何访问您提到的键/值对。
  • 实际上在这里我没有针对文档 ID 进行查询。我已针对员工 ID 进行了查询。服务调用对吗?你有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2018-04-07
  • 2017-09-07
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
相关资源
最近更新 更多