本文讲述如何使用angular2的http服务来去一台由SpringMVC发布的rest服务的服务器上拉取数据。
我们现来上服务端代码,
@ResponseBody
@RequestMapping("/hero")
public Object getData(HttpServletResponse response) {
//服务器端跨域的配置
response.setHeader("Access-Control-Allow-Origin","*");
logger.warn("得到调用.....");
System.out.println(new Hero().getName() );
Hero hero = new Hero();
hero.setName("张三李强");
return hero;
}
response.setHeader("Access-Controller-Allow-Origin","*");这行代码是为了允许跨域, 所谓的跨域这里笔者简单的讲一下,就是访问不同域的时候,是否允许跨域的一个问题。
javascript请求的网络地址只要协议、域名、端口有任何一个不同,都被当作是不同的域。
打一个比方 http://www.test.com/ 和
http://www.test.com:8080就是不同的域
服务器端的rest服务就讲到这里。
现在来讲客户端的实现。
angular2采用的编程语言是typescript。
类似于其他的MVVM框架。angular2同样的进行了组件化。
这里笔者写了三个文件
student.component.ts //组件文件
student,service.ts //服务文件
student.ts //实体文件
组件代码调用服务代码,服务的代码发起http请求从rest服务器上拉取数据
这里笔者直接上代码了,代码的注释都已经很详细了。足以说明问题
student.component.ts
import {Component, OnInit} from "@angular/core";
import {StudentService} from "./student.service";
import {Student} from "./student";
@Component({
moduleId: module.id,
selector: 'student',
template: `{{title}}`,
providers: [StudentService],
})
//实现了OnInit接口以便于加载完组件就进行从服务器端抓取数据
export class StudentComponent implements OnInit {
title = '这是学生组件用于演示ng2从springmvc服务器端拉取数据';
students: Student[];
//注入StudentService服务
constructor(private studentService: StudentService) {
}
//组件被加载立即去rest服务器上拉取数据
ngOnInit(): void {
this.getStudent();
}
getStudent() {
this.studentService.getStudent().then(students => console.log()
, error => console.log(error));
}
}
student,service.ts
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Student} from "./student";
@Injectable()
export class StudentService {
//从指定的地址拉取数据
private url = 'http://localhost:8080/hero';
constructor(private http: Http) {
}
getStudent(): Promise<Student[]> {
return this.http.get(this.url).toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
//将拿到的hero数据进行打印....
console.log("即将开始对Student数据的打印-----");
console.log(body['name']);
console.log("结束对Student数据的打印-----");
return body;
}
private handleError (error: Response | any) {
console.log("有错误???");
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Promise.reject(errMsg);
}
}
student.ts
//自己封装的实体
export class Student {
constructor(public id: number, public name: string) {
}
}
完整的代码地址是: http://download.csdn.net/detail/u013803262/9752256
代码在myNg2_http_demo这个分支上,代码在app/student文件夹下。
至于服务器端只需要在springMVC的controller类中加入一个被@RequestMapping注解修改的方法即可,直接返回pojo对象就可以了。