一。
1. 使用命名#ng g component requestStyle,来创建一个新的演示组件,并通过selector来添加到ponent.html中,以起到添加到主页中显示的目的。
2. 后天的代码是用express,node环境配置的web服务器,支持简单的get,post, jsonp。
3. 在ponent.ts中imports引用HttpModule,JsonpModule(用来支持JSONP)
二:(不是用响应式编程的库RxJS)。
1. 通过Http, Jsonp请求数据,不用RxJs(主要用来实现响应式编程的包,主要用于异步编程,Angular引入RxJS为了实现异步可控,更简单)
a. 在类的构造器中引入http,jsonp(jsonp时使用):
constructor(private http: Http, private jsonp: Jsonp) { }
b. 使用Http的get获取数据:
1 getDataByGet() {2this.http.get('http://localhost:3000/news').subscribe((data)=>{3 console.log(JSON.parse(data['_body'])['msg']);4},5(error) => {6 console.log(error); 7 }); 8 }
2. 使用jsonp跨域来从服务器中去获取数据
a. 首先要在需要使用的jsonp的类的构造函数中引入Jsonp:
constructor(private http: Http, private jsonp: Jsonp){}
b. 需要特别注意的是:使用jsonp时需要在路径中添加回调函数即(callback=JSONP_CALLBACK)
getDataByJsonp() {this.jsonp.get('http://localhost:3000/news?callback=JSONP_CALLBACK').subscribe((data)=>{console.log(data['_body']['msg']);}, (error) => {console.log(error);})}
3. 使用http的post方法来与服务器进行通信;(注意:在这种方式的通信中,需要设置添加headers.)
a, 首先需要引入Headers, 即 import { Headers } from '@angular/http';
b. 然后在类中实例化Headers: 即:private headers: Headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'});
c. post的格式为:this.http.post(url, JSON.stringify(数据对象),{headers: this.headers}).subscribe();
1 getDataByPost() {2 // 当使用post请求时要设置header,即请求的header对象,post的请求的参数为(url,postData,header)3this.http.post('http://localhost:3000/dologin',JSON.stringify({'username': 'xiaoxiao'}),{headers: this.headers}).subscribe((data)=>{4 console.log(JSON.parse(data['_body'])['msg']);5},6(error) => {7 console.log(error); 8 }); 9 }
三:(使用RxJS的库来实现get,post ,jsonp获取数据,实现响应式编程)
需要用到请求数据的地方引入Http模块Jsonp模块,以及rxjs.
RxJS是一种针对异步数据流编程工具,或者叫响应式扩展编程;他的目标主要是异步编程,Angular引用的RxJS为了就是让异步可控,更简单。
大部分的RxJS操作符都不包括在Angular的Observable基本实现中,基本实现只包括Angular中本身所需的功能。
如果想要更多的RxJS功能,我们必须导入其所定义的库来扩展Observabe对象,以下是这个模块所需导入的所有的RxJS操作符:
1. 首先,引用Http, JSONP, RxJS 模块
1 import {Http, Jsonp} from '@angular/http';2 import {Observable} from 'rxjs';3 import 'rxjs/Rx';
注:我们所做的最后一行的作用是只是导入这个库,加载并运行其中的脚本,他会把操作符添加到Observable类中。
2. 构造函数中声明:
1 constructor(private http: Http, private jsonp: Jsonp) {}
3. 对get , post , jsonp的方法函数进行一些类的改造如下:
get方法:
getDataByRXGet() {this.http.get('http://localhost:3000/news').map(res => res.json()).subscribe((data)=>{console.log(data);},(error) => {console.log(error);});}
post方法改造:
1 getDataByRXPost() {2// 当使用post请求时要设置header,即请求的header对象,post的请求的参数为(url,postData,header)3this.http.post('http://localhost:3000/dologin',JSON.stringify({'username': 'xiaoxiao'}),{headers: this.headers})4.map(res => res.json())5.subscribe((data)=>{6 // console.log(JSON.parse(data['_body'])['msg']);7 console.log(data);8 }, 9 (error) => { 10 console.log(error); 11 }); 12 }
jsonp方法改造:
1 getDataByRXJsonp() {2this.jsonp.get('http://localhost:3000/news?callback=JSONP_CALLBACK')3.map(res => res.json())4.subscribe((data)=>{5 // console.log(data['_body']['msg']);6 console.log(data);7}, (error) => { 8 console.log(error); 9 }) 10 }