简体   繁体   中英

Angular2 Promise : How to use the response from Http Get

I'm new to Angular and following this tutorial to learn the basics. Consider the following http get call.

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

After converting the observable to a promise, how can I really utilize the response(eg console log, parse and access a response element.. etc) using a function inside the then() clause?

I tried the following, even though it logs the Response, I can't really access anything in the response object.

this.http.get(url, {headers : this.headers})
                        .toPromise()
                        .then(function(res) {
                                console.log(res);
                                return res => res.json().data as Query[];
                        })
                        .catch(this.handleError);

Any help would be much appreciated. Thank you.

Angular2 use RXjs observable instead of promises. It work as follows.

create httpService as follows.

httpService.ts

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

declare let ApiUrl : any;

@Injectable()
export class httpService {
    constructor(private http: Http){}

    getHeader = () => {
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');

        return headers;
    };

    request = (req) => {
        let baseUrl = ApiUrl,
            requestOptions = new RequestOptions({
            method: req.method,
            url: baseUrl+req.url,
            headers: req.header ? req.header : this.getHeader(),
            body: JSON.stringify(req.params)
        });

        return this.http.request(new Request(requestOptions))
                        .map((res:Response) => res.json());
    }
}

Now simply use this service in your components/directives as below:

componenet.ts

import {Component, Inject, Directive, Input, ElementRef} from '@angular/core';

@Directive({
  selector: '[charts]' // my directive name is charts
})
export class chartsDirective{

  constructor(@Inject('httpService') private httpService){}

  ngOnInit(){

    this.httpService.request({method: 'POST', url: '/browsers', params:params, headers: headers})
            .subscribe(
                data => self.data = data, //success
                error => console.log('error', error),
                () => {console.log('call finished')}
            )
  }
}

And lastly you justt need to add your httpService to provider of ngModule:

appModule.ts

import {NgModule} from '@angular/core';
import {ApiService} from "./api.service";

@NgModule({
    providers: [
        {provide : 'httpService', useClass : httpService}
    ]
})

export class apiModule{}

Now, You can use httpService anywhere in your code by injecting like we did in component.ts

here an example of how you can do it.

Not necessary but gives a nice code structure create a service which handles all your user requests:

User Service

@Injectable()
export class UserService {

   constructor(private http: Http) { }

   getById(id: string): Observable<User> {
      return this.http.get("http://127.0.0.1" + '/api/CustomUsers/' + id)
      // ...and calling .json() on the response to return data
      .map((res: Response) => {
         var user = User.withJSON(res.json());
         return user;
      })
      //...errors if any
      .catch((error: any) => Observable.throw(error));
   }
}

So here we fetch the user with a given id and creates a user object with the returned json.

User Model

export class User {

    constructor(public id: string, public username: string, public email: string) {

    }

    static withJSON(json: any): User {

        // integrity check
        if (!json || !json.id || !json.username || !json.email) { return undefined; }

       var id = json.id;
       var username = json.username;
       var email = json.email;

       // create user object
       var user = new User(id, username, email);
       user.firstname = firstname;

       return user;
   }

Service call

this.userService.getById(this.id).subscribe(user => {
    this.user = user;
  },
    err => {
       console.error(err);
    });

Hope this helps

I had a similar issue. After debugging the response object I found that data did not exist on the res.json() object. Change to this instead:

this.http.get(url, {headers : this.headers})
                    .toPromise()
                    .then(function(res) {
                            console.log(res);
                            return res => res.json() as Query[];
                    })
                    .catch(this.handleError);

Notice all I did was change the line that reads return res => res.json().data as Query[];

to return res => res.json() as Query[];

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