按 console.log 显示 angular 8 中的可观察数组

showing by console.log an observable array in angular 8

我试图在控制台上显示来自我的 angular 项目中的服务的可观察响应。但它似乎未定义。当我尝试使用循环时,控制台中的错误表明它不可迭代,而可观察对象应该 return 一个数组。为什么会这样?

组件

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

  heroes: Hero[];          

  constructor(private heroService: HeroService, private messageService: MessageService) { }

  getHeroes(): void {
    this.heroService.getHeroes()
    .subscribe(data => this.heroes = data);     
  }


  ngOnInit() {
    this.getHeroes();
    // for(let hero of this.heroes){
    //   console.log(hero);
    // }
    console.log(this.heroes);
  }

}

服务

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

  private heroesUrl = 'api/heroes';  

  constructor(
    private messageService: MessageService,
    private http: HttpClient
  ) { }

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  getHeroes(): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap(_ => this.log('fetched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
  }


  private log(message: string) {
    this.messageService.add(`HeroService: ${message}`);
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      console.error(error); 

      this.log(`${operation} failed: ${error.message}`);

      return of(result as T);
    };
  }

}

发生这种情况是因为请求是异步的,这意味着程序会在请求得到解决时继续执行。

在其他情况下,您应该在解决请求时使用请求的结果。在您的示例中,您将请求的返回值分配给 heroes 属性.

getHeroes(): void {
  this.heroService.getHeroes()
    .subscribe(data => {
      this.heroes = data; // <- after this point you have the result 
      console.log(this.heroes);
  });     
}