一. app.module.ts注册http jsonp服务
引入HttpModule、JsonpModule
普通的http调用并不需要用到JsonpModule,不过稍后我就会演示对jsonp的支持,所以现在就加载它,免得浪费时间。
import { HttpModule,JsonpModule } from '@angular/http';
HttpModule、JsonpModule依赖注入
imports: [BrowserModule,AppRoutingModule,BrowserAnimationsModule,FormsModule,ReactiveFormsModule,HttpClientModule,NgZorroAntdModule,DragDropModule,DelonChartModule.forRoot(),HttpModule,JsonpModule],
二. 通过http、jsonp请求数据——get
创建服务,引入Http、Jsonp模块
ng g service service/test
构造函数内声明
constructor(private http:Http,private Jsonp:Jsonp) { }
在service中定义方法,发送get请求,并返回对应接口得到的数据
getData(){const url="/appapi.php?a=getPortalList&catid=20&page=1";return this.http.get(url);}
在对应页面导入test.service
import { TestService } from '../../service/test.service';
导入RxJs,使用RxJs库中的方法处理数据
import {Observable} from "rxjs";import "rxjs/Rx";
在构造函数中注册testService
constructor(private testService:TestService) { }
调用service中封装好的getData()方法获取数据
requestData(){this.testService.getData().subscribe((data) => {console.log(JSON.parse(data['_body'])['result']);this.list=JSON.parse(data['_body'])['result'];},error => this.error = error);}
subscribe里面封装了请求成功的回调和失败的回调
Jsonp请求,请求路径后注意加上callback后的内容
三. 通过http请求数据——post
post与get的不同之处在于,post请求数据要传三个参数,即url、data(页面调用post方法传入)、header。引入注册header
import { Http,Jsonp,Headers } from '@angular/http';
3.发起请求
postData(val){const url="http://127.0.0.1:3000/dologin";return this.http.post(url,JSON.stringify(val),{headers:this.headers})}
页面调用
postValue(){this.testService.postData(this.data).subscribe((data)=>{console.log(data);},error=>{console.log(error)})}
四. 通过http请求数据——delete
service中发起请求
deleteHero (id: number): Observable<{}> {const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42return this.http.delete(url, headers).pipe(//管道函数catchError(this.handleError('deleteHero')));}
页面调用
this.heroesService.deleteHero(hero.id).subscribe();
该组件不会等待删除操作的结果,所以它的 subscribe (订阅)中没有回调函数。不过就算你不关心结果,也仍然要订阅它。调用 subscribe() 方法会执行这个可观察对象,这时才会真的发起 DELETE 请求。
**你必须调用 subscribe(),否则什么都不会发生。仅仅调用 HeroesService.deleteHero() 是不会发起 DELETE 请求的。**
五. 通过http请求数据——delete
put与post方法一致,三个参数,url、data(请求体)、headers
service发起请求
updateHero (hero: Hero): Observable<Hero> {return this.http.put<Hero>(this.heroesUrl, hero, headers).pipe(catchError(this.handleError('updateHero', hero)));}
页面调用
putValuethis.testService.updateHero (this.data).subscribe((data)=>{console.log(data);},error=>{console.log(error)})}