-1

I'm trying to assign array from service to my local variable in component and display it in console from component's method. unfortunately result is always 'undefined'. What I've tried so far:

  1. I'm initializing data in service by using OnInit() in component. I'm doing it by calling my initialize method which assigns data from .json file to local variable.
  2. After initializing, I'm trying to assign result from getMovies method (which is array) to local variable
  3. I'm testing if this worked using console.log

I don't understand why, but when I'm trying to write something in console like this everything works.

testMethod(): void {
  console.log(this.testService.getMovies()[0]);
}

I want to assign result of this.testService.getMovies() to local variable and achieve something like this:

testMethod(): void {
  console.log(this.movies[0]);
}

Here's my code:

Service:

export class MovieTestService {

  constructor( private http: HttpClient ) { }

  movies: IMovie[] = new Array<IMovie>();
  private moviesUrl = "assets/movies.json";
  myMovies: Observable<IMovie[]> = this.http.get<IMovie[]>(this.moviesUrl);

  initialize(): void {
    this.myMovies.subscribe({
      next: data => this.movies = data
    })
  }

  getMovies(): IMovie[] {
    return this.movies;
  }
}

Component:

export class TestComponent implements OnInit {
  constructor( private testService: MovieTestService ) { }
  movies: IMovie[] = new Array<IMovie>();

  testMethod(): void {
    console.log(this.testService.getMovies()[0]);
  }

  ngOnInit(): void {
    this.testService.initialize();
    this.movies = this.testService.getMovies()
  }
}

I'm using a translator so if something's unclear please let me know.

Thank you.

Hameti
  • 1
  • 1

1 Answers1

0

In MovieTestService getMovies return HTTP response in Observable instead of making an HTTP request and assigning results to a local variable movies

import { Observable } from 'rxjs';

export class MovieTestService {

  constructor( private http: HttpClient ) { }

  private moviesUrl = "assets/movies.json";

  getMovies(): Observable<IMovie[]> {
    return this.http.get<IMovie[]>(this.moviesUrl);
  }
  
}

Inside component subscribe and assign the result to local variable movies then call testMethod() to available movies data.

export class TestComponent implements OnInit {

    constructor( private testService: MovieTestService ) { }

    movies: IMovie[] = new Array<IMovie>();

    ngOnInit(): void {
        this.testService.getMovies().subscribe(data => {
            this.movies = data;
            this.testMethod();
        });
    }

    testMethod(): void {
        console.log(this.movies[0]);
    }
}
navnath
  • 3,548
  • 1
  • 11
  • 19