'how to and array of objects from a subscribe method and store it in another array for use in functions?
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.
Edit: i can insert the values i need to an array and see the values only problem is they are strings and i need them as number with their name.
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);
}
coord: any[] = [];
getAllUserAddress() {
return this.http
.get<any>(`${environment.baseApiUrl}/userAddress/all`)
.subscribe((response) => {
console.log(response);
this.allAddresses = response;
console.log('all addresses:',this.allAddresses);
this.setLatLong();
});
}
setLatLong() {
this.coord = this.allAddresses.map(
(obj) => ' lat: ' + obj.latitude + ' long: '+
obj.longitude
);
console.log('coord array:', this.coord);
this.setMarkers();
}
Solution 1:[1]
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.
Solution 2:[2]
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);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TommyR22 |
Solution 2 | Luca Q |