I'm new to Angular and following this tutorial to learn the basics. Consider the following http get call.
我是Angular的新手,并按照本教程学习基础知识。考虑以下http get调用。
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?
在将observable转换为promise后,如何使用then()子句中的函数真正利用响应(例如,控制台日志,解析和访问响应元素等)?
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.
任何帮助将非常感激。谢谢。
3 个解决方案
#1
3
Angular2 use RXjs observable instead of promises. It work as follows.
Angular2使用RXjs可观察而不是承诺。它的工作原理如下。
create httpService as follows.
按如下方式创建httpService。
httpService.ts
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
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:
最后你只需要将你的httpService添加到ngModule的提供者:
appModule.ts
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
现在,您可以像在component.ts中一样注入代码中的任何地方使用httpService
#2
1
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.
所以这里我们用给定的id获取用户并使用返回的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
希望这可以帮助
#3
0
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:
我有一个类似的问题。调试响应对象后,我发现res.json()对象上不存在数据。改为:
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[];
请注意我所做的就是将返回res => res.json()。data的行更改为Query [];
to return res => res.json() as Query[];
返回res => res.json()作为Query [];
#1
3
Angular2 use RXjs observable instead of promises. It work as follows.
Angular2使用RXjs可观察而不是承诺。它的工作原理如下。
create httpService as follows.
按如下方式创建httpService。
httpService.ts
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
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:
最后你只需要将你的httpService添加到ngModule的提供者:
appModule.ts
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
现在,您可以像在component.ts中一样注入代码中的任何地方使用httpService
#2
1
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.
所以这里我们用给定的id获取用户并使用返回的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
希望这可以帮助
#3
0
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:
我有一个类似的问题。调试响应对象后,我发现res.json()对象上不存在数据。改为:
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[];
请注意我所做的就是将返回res => res.json()。data的行更改为Query [];
to return res => res.json() as Query[];
返回res => res.json()作为Query [];