angular接口传参

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

 

转载于:https://www.cnblogs.com/boreguo/p/10342598.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值