1
votes

i've been working in a project with Angular 11, where i'm using HttpClientModule and RxJS for cosume the SWAPI. I have this code and i for get the people, but i can't because when try to convert the data to JSON i get the message "property name does not exist on type promise"

My code of this service is:

import { Injectable } from '@angular/core';
import { People } from './people';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import 'rxjs/add/operator/catch'
import { HttpClient } from '@angular/common/http';

@Injectable()
export class PeopleService {

  constructor(private http: HttpClient) { }

  getPeople(): Observable<People[]> {
    return this.http
               .get<People[]>("https://swapi.co/api/people")
               .pipe(
                 map(this.toJSON),
                 catchError(err => this.handleError)
               )

  }

  private toJSON(res: Response) {
    const json = res.json();
    return json.results || json.data;
  }

}
2
getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl) .pipe( tap(_ => this.log('fetched heroes')), catchError(this.handleError<Hero[]>('getHeroes', [])) ); } As Per Angular Tutorial . Try this one and change it into your code - Kevin Jose
Misread your question. Tell us where you receive the error - Pushkin
I get the error when try to map. map(this.toJSON) - Andres Hernandez

2 Answers

1
votes

By default Angular receives data from an API call as JSON hence there is no need to convert

Simplify your code to


import { Injectable } from '@angular/core';
import { People } from './people';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class PeopleService {

  constructor(private http: HttpClient) { }

  getPeople = ()=>
     this.http.get<People[]>("https://swapi.co/api/people").pipe(
        map(this.extractData),
        catchError(err => this.handleError)
      )

  private extractData = (res: Response) => json.results || json.data;

}

You can have a look at the Below Demo

0
votes

It doesn't look like you're passing anything into the toJSON function; but you are passing the toJSON function to the map.

I'd write this something like this:

map((result) => this.toJSON(result)),

I'd be throwing up a lot of debugger statements to figure out exactly where, and what, the error is. I'm unclear from your post if it is in the toJSON method or in the map pipe function.