我是Angular的新手,并按照本教程学习了基础知识。考虑以下http get调用。
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
将可观察对象转换为承诺之后,如何使用then()子句中的函数真正利用响应(例如,控制台日志,解析和访问响应元素等)?
我尝试了以下操作,即使它记录了响应,也无法真正访问响应对象中的任何内容。
this.http.get(url, {headers : this.headers})
.toPromise()
.then(function(res) {
console.log(res);
return res => res.json().data as Query[];
})
.catch(this.handleError);
任何帮助将非常感激。谢谢。
Angular2使用可观察的RXjs而不是Promise。它的工作方式如下。
如下创建httpService。
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());
}
}
现在,只需在组件/指令中使用此服务,如下所示:
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')}
)
}
}
最后,您只需要将httpService添加到ngModule的提供程序中:
appModule.ts
import {NgModule} from '@angular/core';
import {ApiService} from "./api.service";
@NgModule({
providers: [
{provide : 'httpService', useClass : httpService}
]
})
export class apiModule{}
现在,您可以像在component.ts中一样进行注入,从而可以在代码中的任何位置使用httpService。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句