Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
observable undefined in component - Angular

I have a service that connects with api

export class ConsolidadoApi {
  constructor(private http: HttpClient) { }
  getInvestiments(search?: any): Observable<any> {
    return this.http.get<any>(`${environment.basePosicaoConsolidada}`);
  }
}

Response this api:

https://demo5095413.mockable.io/consolidado

This one is responsible for the logic before reaching the component

@Injectable({
    providedIn: 'root'
})
export class CoreService {
    public test;
    constructor(private api: ConsolidadoApi, private state: StateService) { }

public createMenu() {
    this.api.getInvestiments()
        .subscribe(response => {
            console.log(response.carteiras[0])
           this.products = response.carteiras[0]
           return this.products;
        })
}

In my component

export class MenuComponent implements OnInit {

  constructor( private coreService : CoreService ) {}

  ngOnInit(): void {
    console.log(this.coreService.createMenu())
  }

}

But when createMenu is called in menu.component.ts it comes undefined.

enter image description here

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The raw response is an object. forEach works only on an array. If you are aiming for forEach in 'categorias', you should try

this.test.categorias.forEach()
about 4 years ago · Juan Pablo Isaza Denunciar

0

When you return Observable<any>, that means the argument of the lambda you create when you do subscribe (which you named response) is type any. This doesn't necessary have the function forEach defined (unless the API returns an object with that prototype). That's generally why using any is not good practice; you can't have any expectations on what the object can contain. In fact, it's possible that it's not on object (it could be an array since any is not exclusively an object). If you do want to use forEach, you will want to make sure that response is type array. You can inspect the object's type before using it (e.g. using typeof) and make a judgement on what to call or even just check if the function you're trying to use is defined first, e.g. if (response.forEach !== undefined). You don't actually need to compare to undefined though, so if (response.forEach) suffices. In the examples, I used response, but you can use this.test since they are the same object after the first line in the lambda.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Based on the link you shared, the response is an object. You can log it to the console to confirm.

You can only call for each on an array, so for example, based on the response api, you can call forEach on the property ‘categorias’ and on that array’s children property ‘produtus’

Edit: this answer was based on the op original api and question

https://demo5095413.mockable.io/carteira-investimentos

    public createMenu() {
        return this.api.getInvestiments()
       }

    ngOnit() {
        this.coreService.createMenu().subscribe(x => console.log(x.categorias))};




{
 "codigo":1,
 "categorias":[
    {
       "nome":"Referenciado",
       "valorTotal":23000.0,
       "codigo":"2",
       "produtos":[
          {
           "nome":"CDB Fácil Bradesco",
           "valor":2000.0,
           "codigo":1,
           "quantidade":0.0,
           "porcentagem":0.5500,
           "aplicacaoAdicional":500.0,
           "codigoInvest":1,
           "salaInvestimento":"CDB",
           "permiteAplicar":true,
           "permiteResgatar":true,
           "movimentacaoAutomatica":false,
           "ordemApresentacao":37,
           "horarioAbertura":"08:30",
           "horarioFechamento":"23:59",
           "codigoGrupo":0,
           "codigoMF":"001
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda