Home > Mobile >  how to and array of objects from a subscribe method and store it in another array for use in functio
how to and array of objects from a subscribe method and store it in another array for use in functio

Time:05-13

I have a service to get data from the backend database and display the array of objects that works fine, the only problem is I can not use it outside of the subscribe.

As i want to extract specific values and store them in an array to use with maps and other functions. Is there a way of doing this? code is below.

usersAddress: UserAddressDto[] = [];
ngOnInit() { 
   this.addressService
      .getAllUserAddress()
      .subscribe((address: UserAddressDto[]) => {
         this.usersAddress = address;
      }); 
   //this prints to console an empty array      
   //unless within the subscribe
   console.log('userAddress', this.usersAddress);
}

CodePudding user response:

You can create a Service:

@Injectable()
export class UsersService {
    
    usersAddress = [];

    constructor(
    ) { }

    setUserAddress(address) {
     this.usersAddress = address;
    }

    getUserAddress() {
     return this.usersAddress;
    }


}

you can access it in other components like this:

userService.getUserAddress()

you need to instantiate the service on constructor of yours components:

constructor(
        private userService: UserService,
    ) { }

where UserService is the name of that service.

CodePudding user response:

I think that your code working properly. The problem is the console log that is not waiting the subscription. If you put the console inside subscription function you will see the right data.

usersAddress: UserAddressDto[] = [];
ngOnInit() { 
   this.addressService
      .getAllUserAddress()
      .subscribe((address: UserAddressDto[]) => {
         this.usersAddress = address;
         console.log('userAddress', this.usersAddress);
      }); 
   
}
  • Related