angular学习总结五——发起post、get请求

首先需要在module中inport相关的module:1.HttpModule

ps:我这里为了使app.module.ts写的这个module,所以用exports,一般的写法不用导出

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { HomeComponent } from '../page/home/home.component';
import { ZContainerModule } from '../component/z-container/z-container.module';
import { HomeModule } from '../page/home/home.module';
import { ShareModule } from './share/share.module';
const route: Routes = [
    {
        path: 'home',
        component: HomeComponent
    },
    {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
    },
    {
        path: 'book-movie-music',
        loadChildren: '../page/book-movie-music/book-movie-music.module#BookMovieMusicModule'
    },
    {
        path: '**',
        loadChildren: '../component/empty/empty.module#EmptyModule'
    }
];
@NgModule({
    imports: [
        CommonModule,
        HttpModule,
        HomeModule,
        ZContainerModule,
        RouterModule,
        RouterModule.forRoot(route)
    ],
    declarations: [
    ],
    exports: [
        HttpModule,
        RouterModule,
        ZContainerModule
    ]
})
export class CoreModule { }

具体的用法

import { Injectable, Injector, EventEmitter } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { URLSearchParams, Jsonp } from '@angular/http';
import { Observable } from 'rxjs';
@Injectable()
export class RequestService {
    private http: Http;
    constructor(
        private injector: Injector
    ) {
        this.http = injector.get(Http);
    }
    handleError(error: Response | any): boolean {
        console.error("baseService received request errorr");
        console.log(error);
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        Observable.throw(errMsg);
        return false;
    }
    createRequstParam(data: any, jsonp = false): any {
        let params = new URLSearchParams();
        for (let key in data) {
            params.set(key, data[key])
        }
        // if (jsonp == true) {
        //     params.set('callback', 'JSONP_CALLBACK');
        // }
        return params;
    }
    createHeaders() {
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        return headers;
    }
    checkResponeCode(res: Response) {
        let serverResponse = res.json() as { code: number, desc: string, data: any };

        return serverResponse;
    }
    queryServer(query: { url: string, method: string }, param: any): Promise<any> {
        let form = this.createRequstParam(param);
        switch (query.method) {
            case "post":
                return this.http.post(query.url, form, { headers: this.createHeaders() }).toPromise().then(this.checkResponeCode.bind(this)).catch(this.handleError);
            case "get":
            default:
                return this.http.get(query.url, { search: form }).toPromise().then(this.checkResponeCode.bind(this)).catch(this.handleError);
        }
    }
}
这个service可以作为所有service的基类,子类调用方便,继承时会在构造函数中super()调用父类的构造函数,如果采用直接注入Http的话,基类需要注入别的的时候,会导致修改所有的子类,所以我这里注入的Injector
官方例子采用的请求返回Observable,我更喜欢Promise的写法,所以与官网有点不同
之所以采用这种把请求抽象了一层是方便在处理请求错误时的处理,方便全局状态管理
如果要使用jsonp,需要注入jsonp:Jsonp,将this.http改为this.jsonp,并且也是要在module中import Jsonp,jsonp的回调函数在createRequstParam中添加(就是注释掉的那段)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值