【问题标题】:Getting Undefined after subscribe successfully called in Service订阅成功后在服务中调用未定义
【发布时间】: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.ts constructor 中将this.currentUser = user.uid 替换为this.currentUser = user
  • 如果您使用httpresponse 作为返回类型,请尝试this.currentUser = user.body.result.uid

标签: angular typescript


【解决方案1】:

如果你想在组件初始化时调用 fetchRecipe(),你可以在成功获取数据后将值传递给 fetchRecipe(),

this.authService.getCurrentUser().subscribe(user => {
      this.currentUser = user.uid
      console.log(this.currentUser);
      fetchRecipe(this.currentUser);
})

并访问

fetchRecipe(currentUser : any) {
  use the value here
}

【讨论】:

  • 这是我的标头组件中的服务和 fetchRecipe 方法调用
  • in store recipe 得到 currentUser 但在 fetch Recipe 得到 currentUser undefined 我想你不明白我的问题
  • 我明白了你的问题。理论上,除非没有设置值,否则它不应该发生,按照我建议的方式尝试。
猜你喜欢
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
相关资源
最近更新 更多