【发布时间】:2019-12-01 20:28:28
【问题描述】:
实际上是 Angular 的新手,我正在尝试创建一个食谱应用程序,所以在这里我创建了一个食谱服务,其中有两种方法,即 storeRecipe(),fetchRecipe()
Recipe.Service.ts
这是我的食谱服务中的构造函数
currentUser;
constructor(@Inject(LOCAL_STORAGE) private localstorage: StorageService, private http: HttpClient, private firstore: AngularFirestore, private authService : AuthService) {
this.authService.getCurrentUser().subscribe(user => {
this.currentUser = user.uid
console.log(this.currentUser)
})
}
现在这里订阅 observable 并获取当前登录用户并将该用户保存在 currentUser 当我控制台 currentUser 得到我想要的但在 fetchRecipe 方法中没有得到 currentUser 但在 store Recipe 方法得到 currentUser 如何在fetchRecipe 中获取currentUser,然后当我的组件初始化时我得到配方
存储和获取配方方法
storeRecipe(data) {
let randomId = this.firstore.createId()
console.log(randomId)
return this.firstore.collection('Recipes').doc(this.currentUser).set({ fid: randomId, ...data }).then(i => {
this.recipes.push({ fid: randomId, ...data })
})
}
fetchRecipe() {
console.log(this.currentUser) // <-- here am getting undefined
return this.firstore.collection('Recipes').get().subscribe(data => {
data.docs.map(i => {
this.recipes.push(i.data())
this.loading.emit(false)
})
})
}
【问题讨论】:
-
嗨,您能否将代码包含在问题中,您在哪里调用 fetchRecipe?而且我认为您需要在
Recipe.Service.tsconstructor中将this.currentUser = user.uid替换为this.currentUser = user -
如果您使用
httpresponse作为返回类型,请尝试this.currentUser = user.body.result.uid。
标签: angular typescript