Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  144] [ 2]  / answers: 1 / hits: 20675  / 7 Years ago, thu, february 16, 2017, 12:00:00

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(e.g. 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.


More From » http

 Answers
5

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


[#58917] Tuesday, February 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;