• 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

    
    
  • 相关阅读:
    bzoj 3732: Network 树上两点边权最值
    思维题题集--------一直都很害怕这些题
    Regionals 2014 >> Asia
    小小粉丝度度熊 二分答案 + two pointer
    I
    Binary Strings Gym
    卸载虚拟机时错误关闭了某个服务,使得电脑除了chrome浏览器都不能联网
    双系统给ubuntu增加分区
    tomcat问题
    eclipse:报错信息The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path
  • 原文地址:https://www.cnblogs.com/boreguo/p/10342598.html
Copyright © 2020-2023  润新知