1

tengo esta direccion url:

https://the-books--goncalomatos2.repl.co/books?id=OL26757374M

que tiene esta estructura en el JSON:

    {
    "info_url": "http://openlibrary.org/books/OL26757374M/The_Hobbit",
    "bib_key": "OLID:OL26757374M",
    "preview_url": "https://archive.org/details/TheHobbitByJRRTolkienEBOOK",
    "thumbnail_url": "https://covers.openlibrary.org/b/id/8406761-S.jpg",
    "details": {
        "covers": [
            8406761
        ],
        "latest_revision": 3,
        "ocaid": "TheHobbitByJRRTolkienEBOOK",
        "edition_name": "Reset edition",
        "title": "The Hobbit",
        "languages": [
            {
                "key": "/languages/eng"
            }
        ],
        "oclc_numbers": [
            "889908756"
        ],
        "type": {
            "key": "/type/edition"
        },
        "revision": 3,
        "publishers": [
            "HarperCollins"
        ],
        "description": {
            "type": "/type/text",
            "value": "The Hobbit is a tale of high adventure, undertaken by a company of dwarves in search of dragon-guarded gold. A reluctant partner in this perilous quest is Bilbo Baggins, a comfort-loving unambitious hobbit, who surprises even himself by his resourcefulness and skill as a burglar.\r\n\r\nEncounters with trolls, goblins, dwarves, elves and giant spiders, conversations with the dragon, Smaug, and a rather unwilling presence at the Battle of Five Armies are just some of the adventures that befall Bilbo.\r\n\r\nBilbo Baggins has taken his place among the ranks of the immortals of children’s fiction. Written by Professor Tolkien for his own children, The Hobbit met with instant critical acclaim when published.\r\nSource: https://www.harpercollins.co.uk/9780007322602/the-hobbit/"
        },
        "physical_format": "Epub",
        "last_modified": {
            "type": "/type/datetime",
            "value": "2019-03-06T18:26:56.281441"
        },
        "key": "/books/OL26757374M",
        "publish_places": [
            "London, England"
        ],
        "classifications": {},
        "created": {
            "type": "/type/datetime",
            "value": "2019-03-06T18:22:06.306781"
        },
        "identifiers": {
            "google": [
                "U799AY3yfqcC"
            ]
        },
        "isbn_13": [
            "9780007322602"
        ],
        "isbn_10": [
            "0007322607"
        ],
        "publish_date": "2009 03",
        "copyright_date": "1995",
        "works": [
            {
                "key": "/works/OL262758W"
            }
        ],
        "cover": "http://covers.openlibrary.org/b/OLID/OL26757374M-M.jpg"
    },
    "preview": "full"
}

desde angular tengo esto en mi api-service:

  private _adaptBookFromServe( data:any ): Book {
    return {
      id: data.id,
      title: data.title,
      author: data.author_name[0],
      description: data.description,
      cover: data.cover


    }
  }

  private _adaptBooksFromServe(data: DocsServer): Book[] {
    return data.docs.map<Book>(serverBook => this._adaptBookFromServe(serverBook));
  }

y tambien desde el api-service hago el get con esto:

  getBook(id: any): Observable<Book> {
    if (this.booksCache[id]) {
      return this.http.get(`https://the-books--goncalomatos2.repl.co/books?id=${id}`).pipe(
      map<any, Book>(book => this._adaptBookFromServe(book)),
      )
  };    
  }

mis interfaces:

interface BooksDictionary{ 
    [id: string]: Book;

}

interface Book {
    id: string;
    title: string;
    author: string[];
    description: string;
    cover: string

}

interface Docs {
    id: string;
    name: string;
}

interface DocsServer {
    docs: any[];
}

interface Resume {
    info: string;
        title: string[];
    name: string;
    author: string;
    resume: string;
    cover: string
}

el error es:

core.js:6014 ERROR TypeError: Cannot read property '0' of undefined
    at ApiService._adaptBookFromServe (api.service.ts:26)
    at MapSubscriber.project (api.service.ts:60) 

que son la linea author: data.author_name[0], y map<any, Book>(book => this._adaptBookFromServe(book)),

lo que quiero es traer medesde la url con el JSON dado es(title, description,cover):

     "details": { 
"title": "The Hobbit",
"description": { "value": "The Hobbit is a tale of high adventure, undertaken by a company of dwarves in search of dragon-guarded gold. A reluctant partner in this perilous quest is Bilbo Baggins, a comfort-loving unambitious hobbit, who surprises even himself by his resourcefulness and skill as a burglar.\r\n\r\nEncounters with trolls, goblins, dwarves, elves and giant spiders, conversations with the dragon, Smaug, and a rather unwilling presence at the Battle of Five Armies are just some of the adventures that befall Bilbo.\r\n\r\nBilbo Baggins has taken his place among the ranks of the immortals of children’s fiction. Written by Professor Tolkien for his own children, The Hobbit met with instant critical acclaim when published.\r\nSource: https://www.harpercollins.co.uk/9780007322602/the-hobbit/"
        },
"cover": "http://covers.openlibrary.org/b/OLID/OL26757374M-M.jpg"}

agradeceria mucho el saber si es que tengo que modificar mis interfaces o algun componente, ya que desde el navegador veo el error pero tambien veo que esta leyendo el url y me trae la informacion del json, lo unico es que no lee la informacion especifica

3
  • Dentro de _adaptBookFromServe( data:any ): has un console.log para ver que te está devolviendo tu api. El error que te marca es que data.author_name[0] no existe. Puede que el hombre que estés poniendo sea incorrecto o que verdaderamente no estés recibiendo nada.
    – Legna
    Commented el 20 mar. 2020 a las 14:52
  • Hola, gracias por responder al usasr este codigo: ` this.http.get(http://localhost:3000/books?id=${id}).subscribe(responseData => console.log(responseData))` veo que si trae la informacion toda del segundo link pero pareciera que esta leyendo de otro lado
    – ecanro
    Commented el 20 mar. 2020 a las 15:29
  • Pues eso, que la respuesta que estás recibiendo no contiene el campo author_name
    – Legna
    Commented el 20 mar. 2020 a las 16:06

1 respuesta 1

0

lo solucione de la siguiente forma(obviamente puede haber muchas otras formas), ya que el json de respuesta del api varia de id a id, que es el desafio principal, en el modelo(interface) modifique lo siguiente:

interface BooksDictionary{ 
    [id: string]: Book;

}

interface Book {
    id: string;
    title: string;
    author: string[];
}

interface Docs {
    id: string;
    title: string;
    author: string;
}

interface DocsServer {
    docs: any[];
}

interface ResumeDictionary {
    [id: string]: Resume
}
interface Resume {
    title: string;
    info: string;
    resume: string;
    cover: string
}
export { BooksDictionary, Book, Docs, DocsServer, Resume, ResumeDictionary }

en el api service:

// some books have diferents json parameters
  private _adaptBookFromServe( data:any ): Book {
    return {
      id: data.id,
      title: data.title,
      author: data.author_name,
    }
  }

  private _adaptResumeFromServe(data: any): Resume {
      return {
        info: data.info_url,
    //some books not have cover, maybe a conditional?
        cover: data.details['cover'],
        title: data.details['title'],
    //if description is type string catch else catch value objet, else  show text
        resume:
          typeof(data.details.description) == 'string' ? data.details.description :
          typeof(data.details.description) == 'object' ? data.details.description.value :
            'Resume unavailable'
    }
  }

y en la vista:

<div id="resume">
    
    <h1>{{title}}</h1>
    <h2>{{author}}</h2>

    <img src="{{cover}}" alt="">
    
    <h3 [innerHTML]="resume"></h3>

</div>

use el innerHTML ya que el texto del resume trae etiquetas html, y voalá funciona como se espera

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.