【发布时间】:2019-12-23 19:18:15
【问题描述】:
我有一项服务可以为我的应用程序中的每种类型的内容生成 observables。在这个 observable 中,我希望能够使用 firebase 用户 ID 生成动态路径 (collectionPath)。我能够在我的不同模块和组件中检索用户 ID,但在这里我需要在构造函数中传递它,并且我尝试过的所有内容都返回 undefined。如何在构造函数中使用该动态值来为我的 firebase 查询提供动态路径?
编辑:我需要在声明时将 userId 设置为当前登录用户的用户 ID。如果我能做到这一点,其余的都可以正常工作。如果不可能,将其设置为使用服务从父组件传递的值。
我尝试将使用服务的组件中的值传递给像 this.collectionService.userId = [the user ID from a subscribe] 这样的服务值。我对每一步都进行控制台记录,我传递的值是正确的,但读取的值与服务构造函数中使用的一样未定义。
我已尝试检索服务内的值,但无法将其传递给构造函数中定义的路径。我在通过方法将值获取到服务时记录了该值并且可以工作,但它不用于构建路径。
我还尝试使用异步函数设置 userId 并等待。仍然未定义。
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { CategoryINTF } from 'src/app/interfaces/components/handlers/category.interface';
import { AngularFireAuth } from '@angular/fire/auth';
@Injectable({
providedIn: 'root'
})
export class CollectionsService {
private patientsCollection: AngularFirestoreCollection<CategoryINTF>;
private patients: Observable<CategoryINTF[]>;
private user: object;
public userId: string;
private albumId: string;
private collectionPath = 'users/' + this.userId;
constructor(
db: AngularFirestore,
authInfo: AngularFireAuth
) {
// OBSERVABLES
// PATIENTS
this.patientsCollection = db.collection<CategoryINTF>(this.collectionPath + '/patients'); // <-- THE PATH I NEED TO SET
this.patients = this.patientsCollection.snapshotChanges().pipe(map(
actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return {id, ...data};
});
}
));
}
async setPatient(Uid: string, id: string, catLabel: string) {
this.userId = Uid;
await this.userId;
console.log("setPatient fired!!!");
console.log("userId: " + this.userId); //correct
console.log("collectionPath: " + this.collectionPath);//undefined
return this.patientsCollection.doc(id).set({
'label': catLabel,
'id': id });
}
testUserID(id: string) {
this.userId = id;
console.log("GOT IT???: " + this.userId); // <-- logs correctly
}
}
创建新患者文档时,应使用 userId 值创建动态路径。目前,该用户始终在路径中返回 undefined,因此患者文档是在 firebase 中 id 为“undefined”的用户下创建的。写操作正在工作,只是不在它应该工作的地方。
我猜我忽略了构造函数的工作原理......帮助。
【问题讨论】:
标签: angular firebase ionic-framework ionic4 angularfire2