首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用console.log显示一个角度为8的可观测阵列

用console.log显示一个角度为8的可观测阵列
EN

Stack Overflow用户
提问于 2020-06-16 03:03:42
回答 1查看 2.2K关注 0票数 1

我正在尝试显示来自控制台的响应,它来自于我的角度项目中的一个服务。但它似乎还没有定义。当我尝试使用循环时,控制台中的错误说它是不可迭代的,而可观察的则应该返回一个数组。为什么会发生这种事?

组件

代码语言:javascript
复制
@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);
  }

}

服务

代码语言:javascript
复制
@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);
    };
  }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-16 03:33:14

这是因为请求是异步的,这意味着在解析请求时,程序的执行仍在继续。

在其他情况下,当请求被解析时,您应该使用请求的结果。在您的示例中,这将是在将请求的返回值赋值给英雄属性之后。

代码语言:javascript
复制
getHeroes(): void {
  this.heroService.getHeroes()
    .subscribe(data => {
      this.heroes = data; // <- after this point you have the result 
      console.log(this.heroes);
  });     
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62400272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档