-1

Imagine I have a list of todos to manipulate just after get it from my api, like:

todo.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TodoService {

  private apiUrl: string = "https://jsonplaceholder.typicode.com/todos";

  constructor(private http: HttpClient) { 

  }

  getTodos = (): any => {
    return this.http.get(this.apiUrl)
  }
}

And my component calling it:

import { Component, OnInit } from '@angular/core';
import { TodoService } from './services/todo.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private todoService: TodoService) {

  }

  todos: any[];

  ngOnInit(): void {
    this.getTodos()
    console.log("todos: ", this.todos)
  }

  getTodos = () => {
    this.todoService.getTodos()
      .subscribe((data) => {
        this.todos = data
      })
  }

}

My console.log("todos: ", this.todos) in ngOnInit always return undefined. Is there any way to have my todos outside the subscribe to be manipulate it after filled?

1 Answers1

2

You need to console.log within the getTodos method. Because JS (also TS) run as single-threaded. So, it will execute all static code before responding to observables and other asynchronous tasks.

So, console.log gets executed before the data from service reaches the component.

getTodos = () => {
    this.todoService.getTodos().subscribe((data) => {
       this.todos = data;
       console.log("todos: ", this.todos);
      })
  }
Chandra Kanth
  • 348
  • 2
  • 13