ionic+cordova

Ionic入门-4(使用Angular进行网络请求)

2017-06-21  本文已影响5973人  lhl_012

旧规矩,官网: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<any> {
        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<any> {
        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。如果遇到一些2B些的后台人员,有中文的参数要放到post里面,要不他们乱码不会处理,虽然不关前端屌事,但是他们一定会说是你的原因,相信我,后台都一个尿性。(__) 嘻嘻。

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、使用方法

不多BB,直接上代码

export class HomePage {
  result: string;

  constructor(private http: HttpService) {
  
    this.result = ""
    
    this.http.get("http://gc.ditu.aliyun.com/geocoding?a=%E8%8B%8F%E5%B7%9E%E5%B8%82")
    
    .subscribe(res => {
    
      //返回结果,直接是json形式
      
      this.result = res.lon;
      
    }, error => {
    
      //错误信息
      
    });
  }

网络请求结束了,如果出现问题,很多都是因为跨域,在后面介绍下跨域解决。

上一篇下一篇

猜你喜欢

热点阅读