0

How can we access the data that is outside the subscription in angular ? . I wanted to get and use the result outside.

user component ts

submit(): void {
    const request = this.UserService
      .getUser()
      .subscribe((result) => {
        this.permissions = result[0].permissions
      });

    //I need to access the data here , permissions should not be empty 
    console.log("this.permissions" , this.permissions)

  }

Service

  getUser(): Observable<User[]> {
    return from(this.feathers.service('users').find<User>({ query : { identityId : 8895}}))
    .pipe(
      map((result) => result.data)
    );
  }
  • wrap submit function in `asyn/await`. This will solve your issue – Abdul Basit Apr 26 '20 at 08:32
  • 1
    Does this answer your question? [Angular 2+ wait for subscribe to finish to update/access variable](https://stackoverflow.com/questions/50951779/angular-2-wait-for-subscribe-to-finish-to-update-access-variable) – smithnblack Apr 26 '20 at 08:41
  • @smithnblack no –  Apr 26 '20 at 10:12

2 Answers2

2

The observable with the subscribe is a async task, while the console.log is syncronous. So console.log will run before the subscribe completes, hence you are getting no value, after which when the http observable completes we will have the subscribe running, only then we will have data available on permissions. Modify the code as below.

submit(): void {
    const request = this.UserService
      .getUser()
      .subscribe((result) => {
        this.permissions = result[0].permissions;
        //I need to access the data here , permissions should not be empty 
        console.log("this.permissions" , this.permissions)
      });
}

References.

  1. Event loop
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
0

Here issue is that Observable is not waiting for the response from service call and proceeding to execute the console statement.That's why the value printed through console statement is not the response what you are expecting .

Two solutions are there for this :

1) You can access this.permissions value through out your user component inside any other method once value is set to this variable . Try using this variable inside another method which is getting called after this execution completes .

2) Using async and await and returning Promise object instead of Observable . Then execution will happen in sequence and console statement will get executed only after response is fetched .

user component ts

async submit(): void {
    const request = await this.UserService
      .getUser()
      .then((result) => {
        this.permissions = result[0].permissions
      });

    //I need to access the data here , permissions should not be empty 
    console.log("this.permissions" , this.permissions)

  }

Service

return new Promise((resolve, reject) => {
      from(this.feathers.service('users').find<User>({ query : { identityId : 8895}})).subscribe(response => {
        resolve(response);
      }, reject);
    });