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