前言:
开发模式采用前后端分离,前端用angular(这里指的是angular2,不要和angularjs混淆了),后端采用springBoot,主要介绍下angular与后端接口调用问题。
思路:
其实官网都有调用,只是一些地方要注意到,而往往就是一些小细节或者小问题卡你半天,因此技术点无大小。
前端angular定义了一个服务文件,专门放置与后端接口交互的方法接口,方法接口中采用的是angular的 HttpClient 的get,put,post,delete方法 参数各异,但大多数第一个参数就是后端url,第二个参数视情况而定,详细的可以去angular的官网文档中去查看阅读, 参考:angular httpClient官方文档 后面针对增、删、改、查会给出具体代码;
后端采用springboot,搞技术的人都不陌生,唯一强调一点,也是困扰我半天的地方,就是因为前段会存在跨域问题,所以在后端的接口定义上要加上几个配置注释,此外接收参数时,参数上要加上@RequestBody 配置说明,否则参数实体对象接收为空
具体代码如下:
一,定义前段对象实体
export class UserInfo {
id: number;
userName: string;
password: string;
// public constructor(
// fields?: {
// id: number,
// userName: string,
// password: string
// }) {
// // tslint:disable-next-line:curly
// if (fields) Object.assign(this, fields);
// }
// public constructor(name: string) {
// this.userName = name;
// }
getFullName(): string {
return this.id + ' ' + this.userName;
}
}
二:定义前段接口调用类service.service.ts(为服务类,可用angular命令生成)
ng generate service service
然后填充service代码如下:
import {
Injectable} from '@angular/core';
import {
HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {
Observable, of} from 'rxjs';
import {
UserInfo} from './userInfo';
import {
logger} from 'codelyzer/util/logger';
import {
log} from 'util';
import {
catchError} from 'rxjs/operators';
import {
callHooks} from '@angular/core/src/render3/hooks';
const httpOptions = {
headers: new HttpHeaders({
'content-Type': 'application/json'})
};
@Injectable({
providedIn: 'root'
})
export class ServiceService {
// private static METHOD_DELTE = 'DELETE';
// private static METHOD_POST = 'POST';
// private static METHOD_GET = 'GET';
// private static METHOD_PUT = 'PUT';
private serviceUrl = 'http://127.0.0.1:8080';
constructor(private httpClient: HttpClient) {
}
// 获取列表数据
getUserList(): Observable<UserInfo[]> {
return this.httpClient.get<UserInfo[]>(this.serviceUrl + '/findUserList');
}
// 获取单个数据
getOneUser(id: number): Observable<UserInfo> {
const params = new HttpParams({
fromString: 'id=' + id
});
const findhttpOptions = {
headers: new HttpHeaders({
'content-Type': 'application/json'}),
params: params
};
return this.httpClient.get<UserInfo>(this.serviceUrl + '/findOneUser', findhttpOptions)
.pipe(catchError(this.handleError<UserInfo>('getOneUser id' + id)));
}
// 添加一个新用户
addUser(user: UserInfo)