簡體   English   中英

嘗試獲取 object 時無法設置未定義的屬性“id”

[英]Cannot set property 'id' of undefined when trying to get a object

當我嘗試從 Firestore 的 Firebase 獲取指定用戶時遇到問題。

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 的結果很好。 但是 object(任務)的結果是未定義的。

PS我還有獲取所有用戶和添加新用戶的功能,所以如果相關,請在評論中告訴我

你的代碼行

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

在這種情況下, id不是表格列,而是 Firestore 的文檔 id

這里是firestore的一個例子

因此,在這種情況下,您的Id是紅色的,而不是藍色的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM