【问题标题】:showing by console.log an observable array in angular 8通过 console.log 显示角度 8 的可观察数组
【发布时间】:2020-10-05 13:49:55
【问题描述】:

我试图在控制台上显示来自我的 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);
    };
  }

}

【问题讨论】:

    标签: arrays angular rxjs-observables


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 2019-04-25
      • 2020-11-03
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      相关资源
      最近更新 更多