获取Http.get中的json值

时间:2016-01-31 15:43:38

标签: typescript angular angular2-services

我试图在Angular2中创建一个小例子。我正在做的是当我点击一个按钮时,这会进入公共API并显示引号,但我不能,该值永远不会显示并且我收到了错误

  

无法阅读财产'报价'未定义的   App {4:20]中的[{{quote.contents.quotes.quote}}

我的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')
      );

  }
}

我的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>

如何从服务订阅中获取值并将其放入我的模板?

1 个答案:

答案 0 :(得分:1)

加载模板时quote.contents未定义。我还注意到quote.contents包含和Array。之后我将myAlert()方法更改为:

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

组件:

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

现在有效。

注意TypescriptAngular2我没有很多技能可能还有其他方法。