Angular & Rxjs:如何在返回 Observable 的函数中将 json 映射到对象数组

Angular & Rxjs: How to map json to object array in a function returning Observable

我分享了我在我的项目中使用的 hero.service.ts

// hero.service.ts 

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { Hero } from './hero';
import { MessageService } from './message.service';

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

  private heroesUrl = 'http://localhost:3000/heroes';

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

  getHeroes(): Observable<Hero[]> {
    this.messageService.add('HeroService: fetched heroes');
    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> => {
  
      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead
  
      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);
  
      // Let the app keep running by returning an empty result.
      return of(result as T);
    }
  }
}

// hero.ts
export interface Hero {
    id: number;
    name: string;
}


// heroes.component.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
import { MessageService } from '../message.service';

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

  constructor(private heroService: HeroService) {
    
  }

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

  ngOnInit(): void {
    this.getHeros();
  }

}

当我在 Postman 中使用 Get 方法检查 heroesUrl(http://localhost:3000/heroes) 时,它 returns

[
  { id: 11, name: 'Dr Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
]

但是在我的代码中,我得不到想要的结果。我的代码有什么问题? 我整天都在寻找正确答案,但找不到我想要的。 enter image description here

我在描述中添加了 heroes.components.ts 文件。 而catchError(this.handleError<Hero[]>('getHeroes', []))这部分生成undefined。 当我使用 Nestjs 作为后端时,我尝试使用 app.enableCors() 来启用所有 CORS,但结果是一样的。 感谢您的所有评论。

我可以解决这个问题。这是 CORS 错误。 我使用了 Nestjs 服务器,并在 main.ts

中添加了以下代码
app.enableCors();

很简单。 谢谢。