4

Estoy tratando de aprender Typescript y Angular2. Lo que hago es consultar un servicio publico al momento de hacer click e imprimo la nota celebre, pero estoy obteniendo el siguire error:

Cannot read property 'quotes' of undefined in [{{quote.contents.quotes.quote}} in App@4:20]

Mi Component.ts

import {Component, OnInit, Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS, URLSearchParams} from 'angular2/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app',
  template: `<ul>
                <li (click)='myAlert()'> Helow World</li>
             </ul>
             <div>
              <spam>{{quote.contents.quotes.quote}}</spam>
             </div>`,
  providers: [HTTP_PROVIDERS]
})

export class App {
  public quote: Object;
  public  logError: string;

  constructor(private http: Http){
    this.quote = {};
  }

  myAlert(){
      this.http.get("http://quotes.rest/qod.json").map(res => { return res.json()})
        .subscribe(
          data => this.quote = data,
          err => this.logError(err),
          () => console.log('Random Quote Complete')
      );

  }
}

Mi boot.ts

import {bootstrap} from 'angular2/platform/browser'
import {App} from './component'
import {HTTP_PROVIDERS} from 'angular2/http';

bootstrap(App, [HTTP_PROVIDERS]).catch(err => console.error(err));

Index.html

<html>
  <head>
    <title>Angular 2 QuickStart</title>


    <!-- 1. Load libraries -->
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.1/http.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
    System.config({
      packages: {
        app: {
          format: 'register',
          defaultExtension: 'js'
        }
      }
    });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <app>Loading...</app>
  </body>

</html>

Como hago para obtener la respuesta del servicio en el subscriber y colocarla en el template?

1 respuesta 1

2

El error se produce porque, antes de obtener los datos de servidor, la propiedad quote de tu componente tiene un objeto vacío y el valor de quote.contents es undefined

Creo que lo podrías solucionar guardando en dicha propiedad el texto de la cita directamente.

El código del método myAlert quedaría así:

myAlert(){
  this.http.get("http://quotes.rest/qod.json").map(res => { return res.json()})
    .subscribe(
      data =>  this.quote = data.contents.quotes[0].quote,
      err => this.logError(err),
      () => console.log('Random Quote Complete')
    );
}

Y en la plantilla lo usarías así: <spam>{{quote}}</spam>

1
  • Justo di con esta solución. Gracias de igual forma.
    – Wilfredo
    el 31 ene. 2016 a las 16:31

Tu Respuesta

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

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