第一步
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頁(yè)面
export class TabsPage {
? constructor(
private?com:ComService
? ) {
? let jso={};
? jso["method"]="post";
? ? let url:string = "/api/post";
//此? ?/api? ? 跟第4步有關(guān)聯(lián) ,必須一樣
? let rxjsData = this.com.post(url,jso);
? rxjsData.subscribe((response:any)=>{
? ? console.log("成功啦");
? ? console.log(response);
? },(error:Object)=>{
? ? console.log("出錯(cuò)啦");
? ? 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
? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? },