首先需要在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);
}
}
}