angular http请求的多种传参方式总结

9 篇文章 0 订阅
1.GET

service:

    getData(data): Observable<any> {
        const url = `${this.config.url}/xxx`;
        return this.http.get(url, { params: data }).pipe(
            map(res => res)
        );
    }
    // url拼接方式
    getData2(data): Observable<any> {
        const url = `${this.config.url}/xxx?name=` + data.name +
        '&age=' + data.age +
        '&gender=' + data.gender +
        '&page=' + data.page +
        '&pageSize=' + data.pageSize;
        return this.http.get(url).pipe(
            map(res => res)
        );
    }

调用:

const info = {
   name:xxx,
   age:xxx,
   gender:xxx,
   page:1,
   pageSize:10
}
this.service.getData(info).subscribe(val=>{

})
2.POST

service

   addData(data): Observable<any> {
        const url = `${this.config.url}/addXXX`;
        return this.http.post(url,data).pipe(
            map((res: any) => {
                return res;
            })
        );
    }

调用:

const info = {
	name:xxx,
	age:xxx
}
this.service.addData(info).subscribe(val=>{

})

登录

 login(data): Observable<any> {
      const url = `${this.config.login}`;
      return this.http.post(url, data).pipe(
          map((res: any) => {
              return res;
          })
      );
    }

调用:formData形式传参

const info = {
      username: this.form.value.userName,
      password: this.form.value.password
}
const params = new HttpParams({
  fromObject: info
});
 this.service.login(params).subscribe(val=>{
 
 })

service:

testPost(data):Observabal<any>{
	const url = `${this.config.server}/pushed/dispose`;
	  return this.http.post(url,{},{params:data}).pipe(
	    map((res:any)=>{
	      return res;
	    })
	)
}

调用:

const data = {
	id:1
}
this.service.testPost(data).subscribe(val=>{
})

service:
APPLICATION/JSON

childPolicySubmit(data): Observable<any> {
      const headers = new Headers({
        'Content-Type': 'application/json; charset=utf-8'
      });
      return this.http.post(`${this.config.urlApi}/births/certificates`, data)
      .map((res:any) => res);
}

调用:

const data:any ={};
data.name="xxx";
data.age = 23;
this.service.childPolicySubmit(data).subscribe(val=>{

})
3.PUT

service

   updateData(data): Observable<any> {
        const url = `${this.config.url}/updatexxx`;
        return this.http.put(url,data).pipe(
            map((res: any) => {
                return res;
            })
        );
    }

调用

const info = {
	id:1,
	name:xxx
}
this.service.updateData(info).subscribe(val=>{

})
4.DELETE
// 批量删除
   delMore(data): Observable<any> {
        const url = `${this.config.url}/XXX/remove`;
        return this.http.delete(url, {params: data}).pipe(
            map((res: any) => {
                return res;
            })
        );
    }
    // 单条删除
    delSingle(data): Observable<any> {
        const url = `${this.config.url}/remove/`+ data.id;
        return this.http.delete(url).pipe(
            map(res => res)
        );
    }

调用

//批量删除
	const info = {
      ids: this.selectIds.join(',')
    }
    const params = new HttpParams ({
      fromObject: info
    })
    this.service.delMoreOrg(params).subscribe(val=>{
	
	})
	//单条删除
	const info = {
       id: this.selectIds.join(',')
    }
    this.service.delExp(info).subscribe(val=>{
    
    })
5.解决特殊字符问题(+加号被传成空格)

service

 onlySubmit(data):Observable<any>{
    const info = this.commonFService.forEachData(data);
    const url = `${this.config.server}/report/post`;
    return this.http.post(url,info,
        {
          headers: new HttpHeaders({
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          })
        }
      ).pipe(
        map((res:any)=>{
          return res;
        })
      )
  }

commonFService

 forEachData(data){
    let str='';
    for(let i in data){
      if(i==='urls'){
        for(let j=0;j<data['urls'].length;j++){
          str = str +"urls="+data['urls'][j]+'&';//urls是一个数组
        }
      }else{
        str = str + i+"="+data[i]+'&';
      }
    }
    str = str.substring(0,str.length-1);//去除最后一个&符号
    return str;
  }

component.ts

let data = {
        fileNames: this.attachNames ? this.attachNames.join("|").replace(/\+/g,'%2B') : "",//注意将加号转换为%2b
        attachments: this.attachUrls ? this.attachUrls.join("|").replace(/\+/g,'%2B') : "",
        sourceSystem: "NBXC",
        comment:"",
        infoType: "2",
        urls:this.urlsList
    };
    this.service.onlySubmit(data).subscribe(val=>{
    })
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Angular中,可以使用参数传递来向组件传递数据。有几种不同的方式可以实现参数传递: 1. 通过路由传递参数:可以在路由配置中定义参数,并在URL中传递参数值。在组件中,可以使用ActivatedRoute服务来访问传递的参数。例如: 在路由配置中: ``` { path: 'example/:id', component: ExampleComponent } ``` 在组件中: ```typescript import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.params.subscribe(params => { const id = params['id']; // 使用传递的参数 }); } ``` 2. 通过属性绑定传递参数:可以在组件模板中使用属性绑定来传递参数。在父组件中,使用属性绑定将数据传递给子组件。在子组件中,通过@Input装饰器接收传递的参数。例如: 在父组件模板中: ```html <app-child [param]="value"></app-child> ``` 在子组件中: ```typescript import { Input } from '@angular/core'; @Input() param: any; // 使用传递的参数 ``` 3. 通过服务传递参数:可以创建一个共享的服务,在多个组件之间共享数据。在提供者中定义一个属性来保存要传递的参数,在需要使用参数的组件中注入该服务并访问参数。例如: 创建一个参数服务: ```typescript import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ParamService { param: any; } ``` 在组件中使用参数服务: ```typescript import { ParamService } from './param.service'; constructor(private paramService: ParamService) { } ngOnInit() { const param = this.paramService.param; // 使用传递的参数 } ``` 以上是一些常见的Angular中传递参数的方式,你可以根据你的需求选择适合的方式来传递参数。希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gaiery

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值