简体   繁体   中英

value always undefined when I set it in promise angular typescript

I have a function getData() in accountService.ts. I'm trying to get user data and user account data together in zip promise. Resolve works correctly and I get the correct data, but when I try to set these local variables to the returned values, they are always undefined. I want to set them to use them in other functions.

getData(){
    zip(this.getUser(), this.getAccount()).toPromise().then(data =>{
        this.user = data.values[0];
        console.log(this.user);            
        this.account = data.values[1];
        resolve(data.values[0],data.values[1]);
     });         
}

I use Angular 8 with typescript.

Thanks

Your function getData() seems to return no values. I would follow the below approach

getData(){
    return zip(this.getUser(), this.getAccount()).pipe(
      tap(data => {
        this.user = data.values[0];
        this.account = data.values[1];
      }),
      map(({user, account}) => ({user, account}))
    )       
}

Now we are returning an Observable<{user: any, account: any}> . In the component where this function is used we can access the values using subscribe

ngOnInit() {
  this.accountService.getData().subscribe({
    next: data => {
      // access account using data.account and user using data.user
    }
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM