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?