简体   繁体   English

如何从外部API获取数据?

[英]How to get data from external api?

I'm new to Angular2. 我是Angular2的新手。 I'm going to write single page app and I need possibility to get json from my backend. 我要编写单页应用程序,我需要从后端获取json的可能性。

I found a lot of examples online but no one works for me... :/ I spent 2 days trying to run this and debug... 我在网上找到了很多示例,但没有人适合我...:/我花了2天的时间尝试运行和调试...

I wrote this code: 我写了这段代码:

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/Rx';

export class Comp {
    id:number;
    name:string;
    cmd:string;
    builds:[Build]
}

export class Build {
    id:number;
    name:string;
    status:string;
    component_id:number;
}

@Component({
    selector: 'my-app',
    template: `
      <h1>MYAPP</h1>
      <ul>
        <li *ngFor="#comp of comps">
          <b>{{ comp.name }} <=> {{ comp.cmd }}</b>
          <ul>
            <li *ngFor="#build of comp.builds">
              <b>{{ build.name }} <=> {{ build.id }}</b>
            </li>
          </ul>
        </li>
      </ul>
    `
})
export class AppComponent {

  constructor(private http: Http) {}

  public comps;

  ngOnInit() {
    this.getComps();
  }

  getComps() {
    return this.http.get('http://localhost:4000/components')
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.comps = data},
        err => console.error(err),
        () => console.log(this.comps)
      );
  }
}

I want to get Comp model from web and show it using @template. 我想从网络获取Comp模型并使用@template进行显示。 I tried to debug this in Google Chrome console and this.comps variable is undefined. 我试图在Google Chrome控制台中调试它,并且this.comps变量未定义。 Application gets json from backend, but I don't know why can I use it and store in variable. 应用程序从后端获取json,但我不知道为什么要使用它并将其存储在变量中。 I suppose that I have a small mistake in my code, but I don't know where. 我想我的代码中有一个小错误,但是我不知道在哪里。 :( :(

Can anybody help me? 有谁能够帮助我?

Verify that res.json() in .map((res:Response) => res.json()) contains the data that you think it does. 验证res.json().map((res:Response) => res.json())包含您认为它的数据。

I suggest creating a helper method and setting a breakpoint as follows: 我建议如下创建一个辅助方法并设置一个断点:

getComps() {
    return this.http.get('http://localhost:4000/components')
      .map(this.extractData)
      .subscribe(
        data => { this.comps = data},
        err => console.error(err),
        () => console.log(this.comps)
      );
  }

private extractData(res: Response) {
    if (res.status < 200 || res.status >= 300) {
        throw new Error('Bad response status: ' + res.status);
    }

    //set breakpoint here and value of body.
    let body = res.json();

    //some web servers package the API call return value in a .data object.
    //others do not. So, we check to check...
    if (body) {
        if (body.data) {
            return body.data;
        }
        else {
            return body;
        }
    }
    else {
        return [];
    }

}

I was having the same problem and it turned out that IIS Express was not packaging the return value in a .data object, and without the if(body){...} checking code above, the ngFor was choking on an empty {} object. 我遇到了同样的问题,结果表明IIS Express 并未将返回值包装在.data对象中,并且if(body){...}没有上述if(body){...}检查代码,则ngFor会阻塞空的{}宾语。

it should work :) 它应该工作:)

   @Component({
selector: 'my-app',
template: `
  <h1>MYAPP</h1>
  <ul>
    <li *ngFor="#comp of comps">
      <b>{{ comp?.name }} <=> {{ comp?.cmd }}</b>
      <ul>
        <li *ngFor="#build of comp.builds">
          <b>{{ build?.name }} <=> {{ build?.id }}</b>
        </li>
      </ul>
    </li>
  </ul>
`

cheers 干杯

If your JSON data is an array of Comp object than you have to do these two steps: 如果您的JSON数据是Comp对象的数组,则必须执行以下两个步骤:

  1. export class Comp { id:number; name:string; cmd:string; builds:Build[];//this was your first fault }
  2. public comps; 公共演出; // this should be--> private comps:Comp[]; //这应该是-> private comps:Comp []; you don't need it to be public but it have to be an array/list 您不需要将其公开,但必须是数组/列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM