【问题标题】:Angular & Rxjs: How to map json to object array in a function returning ObservableAngular & Rxjs:如何在返回 Observable 的函数中将 json 映射到对象数组
【发布时间】:2021-02-28 06:57:57
【问题描述】:

我分享了我在项目中使用的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) 时,它会返回

[
  { 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&lt;Hero[]&gt;('getHeroes', []))这部分生成undefined。 当我使用 Nestjs 作为后端时,我尝试使用 app.enableCors() 来启用所有 CORS,但结果相同。 谢谢你们所有的cmets。

【问题讨论】:

  • 请检查您的代码是否是CORS问题?
  • 哪里写着undefined?这个段是如何使用的?
  • 信息丢失,分享你实际调用getHeroes()函数的代码。
  • 我认为应该是catchError(err=&gt;this.handleError&lt;Hero[]&gt;(('getHeroes', [],error),但我可以想象发生了什么
  • 谢谢各位。这是COR的问题。我使用了 Nestjs 服务器并添加了 app.enableCors();按照docs.nestjs.com/security/cors 的指导在 main.ts 中,这是一个简单的解决方案。再次感谢。

标签: angular typescript rxjs observable nestjs


【解决方案1】:

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

app.enableCors();

这很简单。 谢谢。

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2021-11-26
    • 2018-10-17
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2018-01-28
    • 2019-09-18
    相关资源
    最近更新 更多