来自服务

时间:2016-02-06 16:04:15

标签: json angular typescript

我不知道如何从我的模板中打印出JSON数据

如果我在模板中使用: 模板:people: {{people}}或模板:people: {{articles}}
总是进入浏览器:

  

人:[对象对象]

如果我在模板中使用: 模板:people: {{people.totalrecords}}或模板:people: {{articlestotalrecords}}

获取空白值: 人:

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

@Injectable()
class ArticleApi {
  constructor(private http: Http) {}
  getData: string;

  seachArticle(query) {
    const endpoint = 'http://xdemocrm.com/webservicecrm.php';
    const searchParams = new URLSearchParams()
    searchParams.set('object', 'account');
    searchParams.set('action', 'list');   
    return this.http
      .get(endpoint, {search: searchParams})
      .map(res => res.json())
  }

  postExample(someData) {
    return this.http
      .post('https://yourEndpoint', JSON.stringify(someData))
      .map(res => res.json());
  }
}

@Component({
  selector: 'app',
  template: `people: {{people}}`, 
  providers: [HTTP_PROVIDERS, ArticleApi],
})
class App implements OnInit {
  public people;
  constructor(private articleApi: ArticleApi) { }
  public articles: Array<any> = [];

  ngOnInit() {
    this.articles = this.articleApi.seachArticle('obama')
        .subscribe (data => this.people = data) 
  }
}

bootstrap(App)
  .catch(err => console.error(err));
<!DOCTYPE html>
<html>
<head>
  <title>angular2 http exmaple</title>
  <link rel="stylesheet" href="style.css">
  <script src="https://code.angularjs.org/tools/system.js"></script>
  <script src="https://code.angularjs.org/tools/typescript.js"></script>
  <script src="config.js"></script>
  <script src="https://code.angularjs.org/2.0.0-beta.1/angular2-polyfills.js"></script>
  <script src="https://code.angularjs.org/2.0.0-beta.1/Rx.js"></script>
  <script src="https://code.angularjs.org/2.0.0-beta.1/angular2.js"></script>
  <script src="https://code.angularjs.org/2.0.0-beta.1/http.js"></script>
  <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
</head>
<body>
  <app>loading...</app>
</body>
</html>

3 个答案:

答案 0 :(得分:26)

如果你想看json,你只需要这样做:

people: {{people | json}} 

答案 1 :(得分:9)

我想你需要

{{people?.totalrecords}}

让它发挥作用。

您在Angular呈现视图之前获取数据,但响应可能在之后到达。

?.为空时,.totalrecords有角度不评估people

答案 2 :(得分:0)

如果您想要更精美的东西,可以使用HTML <pre>标签:

<pre> {{people | json}} </pre>