zoukankan      html  css  js  c++  java
  • 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

    
    
  • 相关阅读:
    一些小姿势
    <学习笔记>《具体数学》
    【react】报错Need at least a key or a value or a label (only for OptGroup) for [object Object]
    Calibration Checkerboard Collection
    华为云如何建表并创建作业定时调度抽取数据
    HIVE SQL教程
    postgresql 教程
    PC机启用了fiddler代理,在手机或其它机器上连接该代理,无法抓包
    Unity3d的Scroll View组件不能滑动到底的解决方式
    Unity3d让GridLayoutGroup按照子物体的数量自动调整宽高
  • 原文地址:https://www.cnblogs.com/boreguo/p/10342598.html
Copyright © 2011-2022 走看看