Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

angular - 成功在服务中调用订阅后获取未定义(Getting Undefined after subscribe successfully called in Service)

actually am new in angular and am trying to create an recipe app so here what i have created an recipes service in which there is two method ie storeRecipe() , fetchRecipe()

(实际上在角度上是一个新手,正在尝试创建一个食谱应用程序,因此在这里我创建了一个食谱服务,其中有两种方法,即storeRecipe()fetchRecipe())

Recipe.Service.ts here is constructor in my Recipe Service

(这里的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)
    })

  }

Now here am subscribing to observable and getting currently loggedIn User and save that user in currentUser when i console currentUser am getting what i want but in fetchRecipe method am not getting currentUser but in store Recipe method am getting currentUser how to get currentUser in fetchRecipe so then i get recipe when my component Initialize

(现在,这里是订阅观察到的,让目前的loggedIn用户,并保存在用户currentUser当我安慰currentUser我得到我想要什么,但在fetchRecipe方法时没有得到currentUser但在店内配方方法正在逐渐currentUser如何让currentUserfetchRecipe这样的话我的组件初始化时得到配方)

Store and fetch Recipe Method

(存储并获取配方方法)

  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)
      })
    })
 }
  ask by Himanshu Rahi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to call the fetchRecipe() on component initialization, you could just pass the value to the fetchRecipe() once you get the data successfully as,

(如果您要在组件初始化时调用fetchRecipe(),则可以在成功获取数据后将值传递给fetchRecipe(),如下所示:)

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

and access

(和访问)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...