第一步
AppModule
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule
,HttpClientModule
]
第二步 新建service
export class ComService {
constructor(
private http:HttpClient
) { }
get(url:string){
return new Observable((observable)=>{
this.http.get(url).subscribe(response => {
observable.next(response);
},(error)=>{
observable.error(error);
})
});
}
post(url:string,parameter:any){
const httpOptions:any = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'POST,GET',
'Access-Control-Allow-Headers':'x-requested-with, Content-Type',
'x-requested-with':'XMLHttpRequest',
'Authorization':'Bearer '
})
};
return new Observable((observable)=>{
this.http.post(url,parameter,httpOptions).subscribe(response => {
observable.next(response);
},(error)=>{
observable.error(error);
})
});
}
}
第三步
新建page页面
export class TabsPage {
constructor(
private com:ComService
) {
let jso={};
jso["method"]="post";
let url:string = "/api/post";
//此 /api 跟第4步有关联 ,必须一样
let rxjsData = this.com.post(url,jso);
rxjsData.subscribe((response:any)=>{
console.log("成功啦");
console.log(response);
},(error:Object)=>{
console.log("出错啦");
console.log(error);
});
}
}
第四步 新建 proxy.config.json
{
"/api": {
"target":"https://postman-echo.com",
"secure":false,
"loglevel":"debug",
"changeOrigin":true,
"pathRewrite":{
"^/api":""
}
}
}
第五步 angular.json
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build",
"proxyConfig":"proxy.config.json"
},
"configurations": {
"production": {
"browserTarget": "app:build:production"
},
"ci": {
"progress": false
}
}
},