简体   繁体   中英

angular 2 consume REST api

I have the heroes app from angular tutorial and i am trying to make it consume REST API. API is build in DRF. I removed the in memory providers from app.module.ts and added HTTP_PROVIDERS . Here is the app.module.ts file now.

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule, HTTP_PROVIDERS }     from '@angular/http';

import { AppComponent }   from './app.component';
import { routing }        from './app.routing';

import { HeroesComponent }      from './heroes.component';
import { DashboardComponent }   from './dashboard.component';
import { HeroDetailComponent }  from './hero-detail.component';
import { HeroService }          from './hero.service';
import { HeroSearchComponent } from './hero-search.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    routing,
    HttpModule
  ],
  declarations: [
        AppComponent,
        HeroesComponent,
        DashboardComponent,
        HeroDetailComponent,
        HeroSearchComponent,
  ],
  providers: [
    HeroService,
    HTTP_PROVIDERS,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

In hero.service.ts i changed just the url.

import { Injectable } from '@angular/core'
import { Http, Headers, Response } from "@angular/http";

import 'rxjs/add/operator/toPromise'

import { Hero } from './hero'


@Injectable()
export class HeroService{
    private heroesUrl = 'http://127.0.0.1/api/heroes/heroes/';  // URL to web api

    constructor(private http: Http){}

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }

    private post(hero: Hero): Promise<Hero> {
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http
            .post(this.heroesUrl, JSON.stringify(hero), {headers: headers})
            .toPromise()
            .then(res => res.json().data)
            .catch(this.handleError)
    }

    private put(hero: Hero): Promise<Hero> {
        let headers = new Headers();
        headers.append('Content-Type', 'application.json');

        let url = `${this.heroesUrl}/${hero.id}`;

        return this.http
            .put(url, JSON.stringify(hero), {headers: headers})
            .toPromise()
            .then(() => hero)
            .catch(this.handleError)
    }

    delete(hero: Hero): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${this.heroesUrl}/${hero.id}`;

        return this.http
            .delete(url, {headers: headers})
            .toPromise()
            .catch(this.handleError)
    }

    save(hero: Hero): Promise<Hero> {
        if (hero.id) {
            return this.put(hero);
        } else {
            return this.post(hero);
        }
    }

    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.heroesUrl)
            .toPromise()
            .then(response => response.json().data as Hero[])
            .catch(this.handleError);
    }

    getHero(id: number): Promise<Hero> {
        return this.getHeroes().then(heroes => heroes.find(hero => hero.id === id))
    }
}

As far as i can tell from google chrome developer tools i got the answer from django with no problem what so ever but its not showing on the page. No errors in console also.

Headers from api request:

Request URL:http://127.0.0.1/api/heroes/heroes/
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:80
Allow:GET, POST, HEAD, OPTIONS
Connection:keep-alive
Content-Type:application/json
Date:Mon, 22 Aug 2016 11:01:39 GMT
Server:nginx/1.4.6 (Ubuntu)
Transfer-Encoding:chunked
Vary:Accept, Cookie
X-Frame-Options:SAMEORIGIN

Response:

[{"name":"noname","id":1},{"name":"noname3","id":2},{"name":"noname3","id":3},{"name":"noname2","id":4},{"name":"noname2","id":5},{"name":"noname2","id":6}]

Do not know if it is important or not but here are my nginx conf

server {

    listen 80;
    server_name team_up.org;
    charset utf-8;
    root /opt/team_up/team_up-web-client/;
    index index.html;

    location / {
       try_files $uri$args $uri$args/ $uri/ /index.html =404;
    }

}

remove HTTP_PROVIDERS from declarations. HTTP_PROVIDERS are deprecated and aren't needed when importing HttpModule .

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