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:
- 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.
- After initializing, I'm trying to assign result from getMovies method (which is array) to local variable
- 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.