Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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();
               }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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);
      }); 
   
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda