尝试获取对象时无法设置未定义的属性“ id”

时间:2020-06-07 14:50:57

标签: javascript angular typescript firebase

尝试从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 我还具有获取所有用户并添加新用户的功能,因此,如果有必要,请在评论中告诉我

1 个答案:

答案 0 :(得分:1)

您的代码行

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

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

Here an example of firestore

因此,在这种情况下,您的Id是红色的,而不是蓝色的。