javascript - 尝试获取对象时无法设置未定义的属性“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 我还有获取所有用户和添加新用户的功能,所以如果相关,请在评论中告诉我
解决方案
你的代码行
this.id = this.route.snapshot.params.id;
在这种情况下id
,它不是表格列,而是 Firestore 的文档 ID
所以你Id
在这种情况下是红色的,而不是蓝色的。
推荐阅读
- apache-spark - pyspark 变更数据捕获实现
- android - AndroidStudio在signInReport中找不到第二个sha-1键
- c# - 获取基于迭代次数的当前枚举值
- javascript - 将具有相同前缀的对象键拆分为新对象
- spring-boot - 在 Spring Boot 中为 FileUpload 编写包装器:文件不存在
- python - Pytest 在测试期间使用开发 sqlite db - NoneType 对象没有属性驱动程序名
- reactjs - 如何修复 Firebase Cloud Functions 上的“Cannot GET”错误
- c# - WPF 在嵌套网格中动态设置控制列和行
- python - 无法理解如何运行 pyomo 脚本
- qt - Qmake 获取父目录