1、service文件
创建xxx.service.ts文件
import { Injectable, Inject } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' }) export class ErrorConditionService { constructor(private http: HttpClient, @Inject('BASE_CONFIG') private config) { } }
|
BASE_CONFIG在app.module.ts文件中写
providers: [ { provide: 'BASE_CONFIG', useValue: { url: 'myurl' } } ]
|
设置proxy实现跨域
(在项目根目录下新建proxy.conf.json,然后在package.json文件中配置一下)
1)proxy.conf.json代码
{ "/myurl": { "target": "http://10.0.0.0:0000", "secure": true } }
2)修改package.json(ng serve -o --proxy-config proxy.conf.json)
|
2、http请求
post传json格式数据:
const data = { id: 1 } ceshi1(data): Observable<any> { const url = `${this.config.myurl}/xxx/xxxxx`; return this.http.post(url, data).pipe( map((res: any) => { return res; }) ); }
|
post传params格式数据1(传参少且字符短):
const data = { id: 1 }
ceshi2(data): Observable<any> { const url = `${this.config.myurl}/xxx/xxxxxx`; return this.http.post(url, {},{ params: data }).pipe( map((res: any) => { return res; }) ); }
|
post传params格式数据2(传参多且字符长):
const data = { id: 1, text:‘成百上千个字节’ }
const params = new HttpParams({ fromObject: data });
ceshi2(data): Observable<any> { const url = `${this.config.myurl}/xxx/xxxxxx`; return this.http.post(url, params).pipe( map((res: any) => { return res; }) ); }
|
或者(效果同上)
const formData = new FormData(); formData.append('id',1); formData.append('text','成百上千个字符');
ceshi2(data): Observable<any> { const url = `${this.config.myurl}/xxx/xxxxxx`; return this.http.post(url, formData).pipe( map((res: any) => { return res; }) ); }
|
问题:get请求转码
使用angular中所带的get方法进行传参{params: data}时,会转义,对“+”这种特殊符号,会转成“ ”,后端接收到“ ”,无法区分是空还是加号,这种就需要前端在使用get方法(参数值不定)的情况下,不去使用angular所带的方法,把参数中的“+”转为“%2B”【参数.replace(/+/g,"%2B")】,然后自己拼接url,进行传参。
参考链接:https://blog.csdn.net/weixin_33725270/article/details/87219207