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

511
Vistas
how do i assign data from the subscribe call to a local variable in Angular

I have tried to declare the variable inside the ngOnInit() but it goes out of scope. I would like to use the variable to iterate over the data and populate my html component. I have followed the answered questions on the same issue but most of them suggest calling a function inside the subscribe function, unfortunately in my case i just need to view the returned data.

import { Component, OnInit } from "@angular/core";
import { Playlist } from "../playlist";
import { PlaylistService } from "../playlist.service";

@Component({
  selector: "app-market-place",
  templateUrl: "./market-place.component.html",
  styleUrls: ["./market-place.component.css"],
})
export class MarketPlaceComponent implements OnInit {
  _playList: Playlist[] = []; //never gets assigned here

  errorMessage;
  constructor(private playListService: PlaylistService) {}

  ngOnInit() {
    this.playListService.getPlaylist().subscribe({
      next: (playList) => {
        this._playList = playList;
        console.log(this._playList); // am able to log the data but its never assigned to my _playList variable
      },
      error: (err) => (this.errorMessage = err),
    });
  }
}

here is the service class

import { Injectable } from "@angular/core";
import {HttpClient, HttpErrorResponse} from '@angular/common/http'
import { Observable, throwError } from "rxjs";
import {catchError, map, tap} from 'rxjs/operators'
import { Playlist } from "./playlist";


@Injectable({
  providedIn: "root",
})
export class PlaylistService {
  private playListUrl = "https://reqres.in/api/users";

  constructor(private http: HttpClient) {}

  getPlaylist():Observable<Playlist[]> {
    return this.http.get<Playlist[]>(this.playListUrl).pipe(
      map((response) => <Playlist[]>response),
      catchError(this.handleError),
    );
}

private handleError(err:HttpErrorResponse){
  let errorMessage = '';
  if (err.error instanceof ErrorEvent){
    errorMessage = `An error occurred: ${err.error.message}`
  }else {
    errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
  }
  console.error(errorMessage);
  return throwError(errorMessage)
}

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

0

I do not know, what your Playlist object looks like, but maybe I have a simple idea, that could solve your issue. I suppose that console.log can not show the array of your objects. Did you try the following?

console.log(this._playList[0]);
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