Angular 订阅后无法使用\log值

Angular 订阅后无法使用\log值,angular,observable,angular8,Angular,Observable,Angular8,想象一下,在从api获取TODO后,我有一个TODO列表要处理,如: todo.service.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class TodoService { private apiUrl: string = "https://

想象一下,在从api获取TODO后,我有一个TODO列表要处理,如:

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)
  }
}
我的组件称之为:

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
      })
  }

}

ngOnInit中的My
console.log(“todos:,this.todos)
始终返回未定义。有没有办法让我的TODO在订阅之外,以便在填充后对其进行操作?

您需要在gettoos方法中使用console.log。因为JS(也叫TS)是作为单线程运行的。因此,它将在响应可观察任务和其他异步任务之前执行所有静态代码

因此,console.log在来自服务的数据到达组件之前执行

getTodos = () => {
    this.todoService.getTodos().subscribe((data) => {
       this.todos = data;
       console.log("todos: ", this.todos);
      })
  }