怎么在angular2中实现一个Http请求?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
提供HTTP服务
HttpModule并不是Angular的核心模块。 它是Angular用来进行Web访问的一种可选方式,并位于一个名叫@angular/http
的独立附属模块中.
编辑app.module.ts
import{HttpModule,JsonpModule}from'@angular/http';
@NgModule({
imports:[
HttpModule,
JsonpModule
],
})
angular-in-memory-web-api
npminstallangular-in-memory-web-api--save-dev
This in-memory web api service processes an HTTP request and returns an Observable of HTTP Response object in the manner of a RESTy web api.
:base/:collectionName/:id?
GETapi/heroes//allheroes
GETapi/heroes/42//thecharacterwithid=42
GETapi/heroes?name=^j//'j'isaregex;returnsheroeswhosenamestartingwith'j'or'J'
GETapi/heroes.json/42//ignoresthe".json"
之前测试时用的app/mock/user_data_memory_mock.ts数据
import{User}from'../model/User';
import{InMemoryDbService}from'angular-in-memory-web-api';
exportclassUserDataMemoryMockimplementsInMemoryDbService{
createDb(){
constusers:User[]=[
newUser('chenjianhua_a',21,'2290910211@qq.com','123456'),
newUser('chenjianhua_b',22,'2290910211@qq.com','123456'),
newUser('chenjianhua_c',23,'2290910211@qq.com','123456'),
newUser('chenjianhua_d',24,'2290910211@qq.com','123456'),
newUser('chenjianhua_e',25,'2290910211@qq.com','123456'),
newUser('chenjianhua_f',26,'2290910211@qq.com','123456'),
];
return{users};
}
}
编辑app.module.ts
import{InMemoryWebApiModule}from'angular-in-memory-web-api';
import{UserDataMemoryMock}from'./mock/user_data_memory_mock';
@NgModule({
imports:[
InMemoryWebApiModule.forRoot(UserDataMemoryMock),
]
})
导入InMemoryWebApiModule并将其加入到模块的imports数组。 InMemoryWebApiModule将Http客户端模拟的后端服务 forRoot()
配置方法需要UserMemoryMockService类实例,用来向内存数据库填充数据
编辑app/service/user.restful.service.ts
import{Injectable}from'@angular/core';
import{Headers,Http}from'@angular/http';
import'rxjs/add/operator/toPromise';
import{User}from'../model/User';
import{Logger}from'./logger.service';
@Injectable()
exportclassUserService{
privateUSERURL='api/users';
privateheaders=newHeaders({'Content-Type':'application/json'});
constructor(privateLog:Logger,
privatehttp:Http){}
getUserByName(name:string):Promise<User>{
consturl=`${this.USERURL}/?name=${name}`;
returnthis.http.get(url)
.toPromise()
.then(response=>response.json().dataasUser)
.catch(this.handleError);
}
getUsers():Promise<User[]>{
console.log('GetUser!');
returnthis.http.get(this.USERURL)
.toPromise()
.then(response=>response.json().dataasUser[])
.catch(this.handleError);
}
create(name:string):Promise<User>{
returnthis.http
.post(this.USERURL,JSON.stringify({name:name}),{headers:this.headers})
.toPromise()
.then(res=>res.json().dataasUser)
.catch(this.handleError);
}
privatehandleError(error:any):Promise<any>{
console.log('Anerroroccurred:',error);
returnPromise.reject(error.message);
}
}
编辑app/components/app-loginform/app.loginform.ts
import{Component,OnInit}from'@angular/core';
import{Logger}from'../../service/logger.service';
import{UserService}from'../../service/user.restful.service';
import{User}from'../../model/User';
import{Subject}from'rxjs/Subject';
@Component({
selector:'app-loginform',
templateUrl:'./app.loginform.html',
styleUrls:['./app.loginform.css'],
providers:[
Logger,
UserService
]
})
exportclassAppLoginFormComponentimplementsOnInit{
users:User[];
submitted=false;
model=newUser('1','fangfang',22,'2290910211@qq.com','123456');
constructor(
privateLog:Logger,
privateuserService:UserService
){}
ngOnInit():void{
this.userService
.getUsers()
.then(users=>this.users=users);
}
onSubmit():void{
this.userService.getUserByName(this.model.name)
.then(user=>{
console.log('user.name',user[0].name);
console.log('user.password',user[0].password);
if(user[0].name===this.model.name
&&user[0].password===this.model.password){
this.Log.log('loginsuccess!');
this.submitted=true;
}else{
this.Log.log('loginfailed!');
this.submitted=false;
}
})
.catch(errorMsg=>console.log(errorMsg));
}
}
HTTP Promise
Angular 的http.get返回一个 RxJS 的Observable对象。 Observable是一个管理异步数据流的强力方式。
现在,我们先利用toPromise方法把Observable直接转换成Promise对象
看完上述内容,你们掌握怎么在angular2中实现一个Http请求的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注恰卡编程网行业资讯频道,感谢各位的阅读!