1.service
1.1.service的创建命令
ng generate service xxx //生成一个新服务
ng generate service xxx --no-spec //生成一个不带有spec.ts的新服务
1.2.在service.ts中添加方法
import {
Http } from '@angular/http';
export class AppService {
urlRoot = 'http://localhost:8892/';
constructor(private http: Http) {
}
queryTestWebList(urlParams: string) {
const url = this.urlRoot + 'testuser/queryTestWeb/list/' + urlParams;
return this.http.get(url);
}
}
1.3.组件中调用service
import {
AppService} from '../app.service';
export class MenuLeftComponent implements OnInit {
constructor(
private service: AppService
) {
}
ngOnInit() {
}
queryTestWebList(flag: boolean) {
this.service.queryTestWebListHttp(urlParams).subscribe(
dataJson => {
//返回结果处理
},
error => {
}
);
}
}
2.Http两种使用
2.1.引用@angular/http的方式
2.1.1.安装http
npm install @angular/http //安装http
npm install rxjs
在app.module.ts中(imports属性添加)引入@angular/http模块,如下代码:
import {
HttpModule, JsonpModule } from '@angular/http';
@NgModule({
imports: [
JsonpModule,
HttpModule
]
})
2.1.2.get的使用
import {
Http } from '@angular/http';
import {
Observable} from 'rxjs';
constructor(
private http: Http
) {
}
functionXXXX () {
this.http.get(url).subscribe(
dataJson => {
// 用于处理数据
},
error => {
}
);
}
2.1.3.post的使用
2.1.3.1.发送json格式数据
import {
Injectable } from '@angular/core';
import {
Http , RequestOptions, Headers} from '@angular/http';
import {
Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AppService {
urlRoot = 'http://localhost:8892/';
constructor(private http: Http) {
}
saveFormPostHttp(sq: string,
num: string,
name: string,
key: string,
value: string,
type: string,
page: string,
base: string,
): Observable<{
}> {
const url = this.urlRoot + 'testuser/insertTestWeb/';
const params = JSON.parse('{"sq":' + sq + ',"num":' + num + ',' +
'"webName":' + name + ',"webKey":' + key + ',' +
'"value":' + value + ',"webType":' + type + ',' +
'"page":' + page + ',"base":' + base + '}');
const headers = new Headers(); // 使用@angular/http的Headers
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({
headers}); // 使用@angular/http的RequestOptions
return this.http.post(url, params, options);
}
}
说明:后端如果需要使用json格式接收,或者使用 @RequestBody 接收
2.1.3.2.发送form表单数据
HttpClientModule,
import {
Injectable } from '@angular/core';
import {
Http , URLSearchParams, RequestOptions, Headers} from '@angular/http';
import {
Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AppService {
urlRoot = 'http://localhost:8892/';
constructor(private http: Http) {
}
saveFormPostHttp(sq: string,
num: string,
name: string,
key: string,
value: string,
type: string,
page: string,
base: string,
): Observable<{
}> {
const url = this.urlRoot + 'testuser/insertTestWeb2';
const params = new URLSearchParams();
params.set('sq', sq);
params.set('webNum', num);
params.set('webName', name);
params.set('key', key);
params.set('value', value);
params.set('webType', type);
params.set('page', page);
params.set('base', base);
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
const options = new RequestOptions({
headers});
return this.http.post(url, params, options);
}
}
说明:
1.后端使用 @RequestParam 接收;
2.如果使用URLSearchParams,那么Content-Type的格式就必须使用form;如果params使用的是json,则Content-Type的格式就必须使用json;
3.如果Content-Type为form,可以不写options,使用this.http.post(url, params);即可;
2.2.引用@angular/common/http的方式
前提:在app.module.ts中(imports属性添加)引入@angular/common/http模块,代码如下:
import {
HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
2.2.1.新建一个httpClient的service
ng generate service httpClient --no-spec
2.2.1.get请求
import {
Injectable } from '@angular/core';
import {
HttpClient } from '@angular/common/http';
import {
map} from 'rxjs/operators';
import {
HttpResponse} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class HttpClientService {
urlRoot = 'http://localhost:8892/';
options = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=UTF-8'})
};
constructor(private http: HttpClient) {
}
queryList() {
const url = this.urlRoot + 'testuser/queryTestWeb/list/FFFFFFFF/FFFFFFFF/FFFFFFFF/FFFFFFFF/10/1';
return this.http.get<any>(url, this.options).pipe(
timeout(15000),
catchError((error) => this.hanldeSomeError(error))
);
}
private hanldeSomeError(error: any) {
if (error.error instanceof ErrorEvent) {
console.log(' error occurred:', error.error.message);
} else {
console.log(`${
error.status}-${
error.statusText}`);
}
return throwError(new Error('Server Error!'));
}
}
说明:
1.使用pipe中的rxjs方法(timeout/catchError等)对数据进行处理;
2.使用@angular/common/http的时候和使用@angular/http区别,get后面<T>作为接收数据的转化类型(T可以是any,也可以是自定义类),不需要使用rxjs的map函数进行处理,默认是获取body的值进行返回的;
3.options内只能包含一种类型数据,如headers,observe,params,reportProgress,responseType,withCredentials。
4.如果使用observe,如 get(url, { observe: ‘response’ }) 时,数据中提取的是完整的response,这个时候可以使用map进行处理,这个时候<T>时可以不用的。
4.调用方法如下:
clickQueryListByHttpClientGet() {
this.httpClient.queryList().subscribe((data) => {
console.log(data.list);
});
}
2.2.2.post请求
import {
Injectable } from '@angular/core';
import {
HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http';
import {
catchError, timeout} from 'rxjs/operators';
import {
throwError} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpClientService {
urlRoot = 'http://localhost:8892/';
options = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=UTF-8'})
};
constructor(private http: HttpClient) {
}
saveFormPostHttp(sq: string,
num: string,
name: string,
key: string,
value: string,
type: string,
page: string,
base: string,
) {
const url = this.urlRoot + 'testuser/insertTestWeb';
const params = JSON.parse('{"sq":' + sq + ',"num":' + num + ',' +
'"webName":' + name + ',"webKey":' + key + ',' +
'"value":' + value + ',"webType":' + type + ',' +
'"page":' + page + ',"base":' + base + '}');
return this.http.post<any>(url, params, this.options).pipe(
timeout(15000),
catchError((error) => this.hanldeSomeError(error))
);
}
private hanldeSomeError(error: any) {
if (error.error instanceof ErrorEvent) {
console.log(' error occurred:', error.error.message);
} else {
console.log(`${
error.status}-${
error.statusText}`);
}
return throwError(new Error('Server Error!'));
}
}
说明:
1.post<T>的T作为返回数据封装类型,如果是json数据,可以使用any进行接收。
2.options的类型和使用均和get保持一致。
3.调用代码如下:
clickSaveHttpClientPost() {
this.httpClient.saveFormPostHttp('502', '3', '1', '2', '4', '3', '32', '65').subscribe(dataJson => {
console.log(dataJson.flag);
});
}