繁体   English   中英

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

[英]showing by console.log an observable array in angular 8

我试图显示来自我的 angular 项目中的服务的控制台上的可观察响应。 但它似乎是未定义的。 当我尝试使用循环时,控制台中的错误表示它不可迭代,而 observable 应该返回一个数组。 为什么会发生这种情况?

零件

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

}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM