首页 > 解决方案 > 尝试获取对象时无法设置未定义的属性“id”

问题描述

当我尝试从 Firebase、Firestore 获取指定用户时遇到问题。

export class TaskService {
  tasksCollection: AngularFirestoreCollection<Task>;
  taskDoc: AngularFirestoreDocument<Task>;
  tasks: Observable<Task[]>;
  task: Observable<Task>;

  constructor(private afs: AngularFirestore) {
    this.tasksCollection = this.afs.collection('tasks', ref => ref.orderBy('title', 'asc'));
  }

  getTask(id: string): Observable<Task> {
    this.taskDoc = this.afs.doc<Task>(`clients/${id}`);
    this.task = this.taskDoc.snapshotChanges().pipe(map(action => {
      if (action.payload.exists === false) {
        return null;
      } else {
        const data = action.payload.data() as Task;
        data.id = action.payload.id;
        return data;
      }
    }));

    return this.task;
  }

}

这是我的Component.ts文件

export class TaskDetailsComponent implements OnInit {
  id: string;
  task: Task;
  hasHours = false;
  showHoursOnUpdate: false;

  constructor(
    private taskService: TaskService,
    private router: Router,
    private route: ActivatedRoute
  ) { }


  ngOnInit() {
    // Get id from url
    this.id = this.route.snapshot.params.id;
    // Get client
    this.taskService.getTask(this.id).subscribe(task => {
      if (task != null) {
        if (task.hours > 0) {
          this.hasHours = true;
        }
      }
      this.task = task;
    });
    console.log(this.id);
    console.log(this.task);
  }

}

id 的结果很好。但是对象(任务)的结果是未定义的。

PS 我还有获取所有用户和添加新用户的功能,所以如果相关,请在评论中告诉我

标签: javascriptangulartypescriptfirebase

解决方案


你的代码行

this.id = this.route.snapshot.params.id;

在这种情况下id,它不是表格列,而是 Firestore 的文档 ID

这里是firestore的一个例子

所以你Id在这种情况下是红色的,而不是蓝色的。


推荐阅读