Ionic4+Angular

2018-12-13  本文已影响0人  YuJingZhou

官网:https://angular.io/tutorial/toh-pt6

1、简单封装网络请求

新建HttpService.ts,代码如下

import {Http, Headers, RequestOptions}from "@angular/http";

import {Injectable}from "@angular/core";

import "rxjs/add/operator/toPromise";

import "rxjs/Rx";

import {Observable}from "rxjs";

import "rxjs/add/operator/catch";

import "rxjs/add/operator/debounceTime";

import "rxjs/add/operator/distinctUntilChanged";

import "rxjs/add/operator/map";

import "rxjs/add/operator/switchMap";

import "rxjs/add/observable/throw";

@Injectable()

export class HttpService {

constructor(private http: Http) {

}

headers =new Headers({'Content-Type':'application/x-www'});

options =new RequestOptions({headers:this.headers});

//get请求

  get(url:string): Observable {

return this.http.get(url, {

headers:new Headers({

"Accept":"application/json",

"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"

      })

})

.map(res => res.json());

}

//post请求

  post(url:string, body:any): Observable {

return this.http.post(url, body, {

headers:new Headers({

"Accept":"application/json",

"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"

      })

})

.map(res => res.json());

}

}

注:上面执行网络请求,将返回信息转化为json。

2、在src/app/app.module.ts中配置

import {HttpModule}from "@angular/http";

import {HttpService}from "../xxx/HttpService";

@NgModule({

declarations: [

MyApp,

···

],

imports: [

BrowserModule,

IonicModule.forRoot(MyApp),

HttpModule

],

bootstrap: [IonicApp],

entryComponents: [

···

],

providers: [

StatusBar,

SplashScreen,

HttpService,

Camera,

Transfer,

File,

{provide: ErrorHandler,useClass: IonicErrorHandler}

]

})

上面重点:import导入了HttpModule(系统),HttpService(自己写的类),在imports中加入了HttpModule,providers中加入了HttpService。

3、使用方法

export class HomePage {

result:string;

constructor(private http: HttpService) {

this.result =""

    this.http.get("接口地址").subscribe(res => {

//返回结果,直接是json形式

console.log(res)

}, error => {

//错误信息

      });

}

4、proxy.conf.json 配置跨越文件

{

"/youku": {

"target":"https://api.youku.com/",

"secure":false,

"changeOrigin":true,

"pathRewrite": {

"^/youku":""

    }

},"/operation": {

"target":"http://192.168.0.199:8081/",

"secure":false,

"changeOrigin":true,

"pathRewrite": {

"^/operation":""

    }

},"/fdfs": {

"target":"http://127.0.0.1/",

"secure":false,

"changeOrigin":true,

"pathRewrite": {

"^/fdfs":""

    }

}

}

上一篇下一篇

猜你喜欢

热点阅读