简体   繁体   中英

How to get data from external api?

I'm new to Angular2. I'm going to write single page app and I need possibility to get json from my backend.

I found a lot of examples online but no one works for me... :/ I spent 2 days trying to run this and debug...

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. I tried to debug this in Google Chrome console and this.comps variable is undefined. Application gets json from backend, but I don't know why can I use it and store in variable. 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.

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.

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:

  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[]; you don't need it to be public but it have to be an array/list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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