为什么组件无法读取 angular 和 typescript 中服务返回的数据?

Why the component cannot read the data returned by service in angular and typescript?

我花了好几个小时都没搞定。

我写了一个 web api get 方法,其中 returns 一个简单的数组。

 public Hero[] getHeroes() 
        {
            return new Hero[] { new Hero { Id = 1, Name = "Hunain Hafeez-1" }, 
                                new Hero {Id= 2,   Name = "Hunain Hafeez-2" } 
            };
        }

   [HttpGet]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public IEnumerable<Models.Hero> GetHeroes()
    {
        
        LocalHeroes= heroes.getHeroes();

        return LocalHeroes;
    }

现在 angular

service.ts

 getHeroesFromWebAPI(): Observable<any>
  {    

      
        return of(this.http.get<any>("https://localhost:44320/api/values").subscribe(res => JSON.stringify(res)));
     }

在component.ts

 getHeroes(): void
   {
      
      this.heroService.getHeroesFromWebAPI().subscribe( r => {this.HeroesWebAPI= r; 
        console.log("STRINGFIED:"+  this.HeroesWebAPI)});
      
      
   }

HeroesWebAPI: any[]= [];

现在在组件的 getHeroes 方法中,this.HeroesWebAPI returns Object Object 当我尝试 stringify 它时,它抛出 CANNOT CONVERT CIRCULAR STRUCTURE TO JSON错误。

如何解决?

您必须像下面这样修改您的服务。

import {map} from 'rxjs/operators';

getHeroesFromWebAPI(): Observable<any>
{    
  return this.http.get<any>("https://localhost:44320/api/values").pipe(
    map(res => JSON.stringify(res))
  );
}