将 URLSearchParams 转换为 HttpParams - Angular HttpClient
Convert URLSearchParams to HttpParams - Angular HttpClient
我正在尝试将 Angular8 上的 service.ts 的 Http 更新为 HttpClient。
我已经为 HttpClient 和 HttpHeaders 更改了 Http 和 Headers,并且删除了 '.pipe(map((response) => response.json().response ));'.选项 search:params.toString() 在 HttpParams 上不起作用,按照建议,我已更改为仅参数。
但是请求没有正常工作:(
之前(Http)
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Http, Headers, Jsonp } from '@angular/http';
import { Environment } from '../app.component';
//my components imports
@Injectable()
export class CompanyService implements OnDestroy {
private url = Environment.origin;
private urlMainSearch = Environment.MAIN_SEARCH;
private urlSearchAll = Environment.SEARCH_ALL;
private headers = new Headers({
'Accept': 'application/cp+json',
'Content-Type': 'application/json'
});
private headersFile = new Headers({
'Accept': 'application/cp+json',
'Content-Type': 'multipart/form-data; boundary=something'
});
constructor(private http: Http,
private jsonp: Jsonp) { }
ngOnDestroy() {
delete this.http;
}
buscarEmpresas(pesquisa: string): Observable<any> {
return this.http.get(`${this.url}/companies/${pesquisa}/search`, { headers: this.headers })
.pipe(map((response) => response.json().response));
}
buscarEmpresasCache(pesquisa: string): Observable<any> {
return this.http.get(`${this.url}/companies/search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
.pipe(map((response) => response.json().response));
}
buscarEmpresasMicroServico(pesquisa: string): Observable<any> {
return this.http.get(`${this.urlMainSearch}/main-search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
.pipe(map((response) => response.json().response));
}
getEmpresa(id: number): Observable<Retorno<Empresa>> {
return this.http.get(`${this.url}/companies/${id}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
getEmpresaByUrlLink(urlLink: string): Observable<Retorno<Empresa>> {
return this.http.get(`${this.url}/companies/link/${urlLink}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
getEmpresaRatings(id: number): Observable<Retorno<Rating>> {
return this.http.get(`${this.url}/companies/${id}/ratings`, { headers: this.headers })
.pipe(map((response) => new Retorno<Rating>(response.json())));
}
getOperadora(): Observable<Array<Empresa>> {
return this.http.get(`${this.url}/companies/search/operadora/10/1`, { headers: this.headers })
.pipe(map((response) => response.json().map(empresa => new Empresa(empresa))));
}
getTopEmpresas(type: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get(`${this.url}/companies/top?type=${type}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Array<Empresa>>(response.json())));
}
buscarEmpresasPorTipo(tipo: number, pagina: number, tags: Array<number>, continentes: Array<number>,
paises: Array<number>, cidades: Array<number>): Observable<Retorno<Array<EmpresaRating>>> {
// if(!this.resolveUrlSearchBug()) {
let url = `${this.url}/companies/searchtype?number=25&page=${pagina}&type=${tipo}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (continentes && continentes.length > 0) {
const continente = `&continentes=${continentes.join(',')}`;
url = url + continente;
}
if (paises && paises.length > 0) {
const pais = `&paises=${paises.join(',')}`;
url = url + pais;
}
if (cidades && cidades.length > 0) {
const cidade = `&cidades=${cidades.join(',')}`;
url = url + cidade;
}
return this.http.get(url, { headers: this.headers })
.pipe(map((response) => new Retorno<Array<EmpresaRating>>(response.json())));
// }
}
buscarTodasEmpresas(pagina: number, texto: string, tipos: Array<number>, tags: Array<number>, localizacoes: Array<number>):
Observable<Retorno<RankingTodasEmpresas>> {
let url = `${this.urlSearchAll}/company-search-all?texto=${texto}&limit=25&offset=${pagina}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (localizacoes && localizacoes.length > 0) {
const localizacao = `&localizacoes=${localizacoes.join(',')}`;
url = url + localizacao;
}
if (tipos && tipos.length > 0) {
const tipo = `&tipos=${tipos.join(',')}`;
url = url + tipo;
}
return this.http.get(url, { headers: this.headers })
.pipe(map((response) => new Retorno<RankingTodasEmpresas>(response.json())));
}
buscarEmpresasSimilares(tipo: number, idEmpresaPesquisada: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get(`${this.url}/companies/random-searchtype?type=${tipo}&idEmpresaPesquisada=${idEmpresaPesquisada}`,
{ headers: this.headers })
.pipe(map((response) => new Retorno<Array<Empresa>>(response.json())));
}
buscarMenuTags(tipo: number): Observable<Retorno<SuperMenu>> {
// console.log(this.resolveUrlSearchBug());
// if(!this.resolveUrlSearchBug()) {
// console.log('Chamando service.........');
return this.http.get(`${this.url}/companies/searchtype/filtro?type=${tipo}`, { headers: this.headers })
.pipe(map((response) => new Retorno<SuperMenu>(response.json())));
// }
}
cadastrarEmpresa(empresa: Empresa, isByCadFornecedor: boolean = false): Observable<Retorno<Empresa>> {
return this.http.post(`${this.url}/companies?isByCadFornecedor=${isByCadFornecedor}`,
JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
cadastrarEmpresaPreCadastro(preCadastro: EmpresaPreCadastro): Observable<Retorno<Empresa>> {
return this.http.post(`${this.url}/companies/pre-cadastro`,
JSON.stringify(preCadastro), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
adminCadastrarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.post(`${this.url}/companies/admin`, JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
alterarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.put(`${this.url}/companies`, JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
buscarTiposEmpresa(): Observable<Retorno<Array<Tipo>>> {
return this.http.get(`${this.url}/categories`, { headers: this.headers })
.pipe(map((response) => new Retorno<Array<Tipo>>(response.json())));
}
buscarTipoEmpresa(tipo: number): Observable<Retorno<Tipo>> {
return this.http.get(`${this.url}/company-types/${tipo}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Tipo>(response.json())));
}
buscarTipoEmpresaPorUrlLink(urlLink: string): Observable<Retorno<Tipo>> {
if (this.http) {
return this.http.get(`${this.url}/company-types/link/${urlLink}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Tipo>(response.json())));
}
}
atualizarStatus(codigo: number): Observable<any> {
return this.http.put(`${this.url}/company-status`, JSON.stringify(codigo), { headers: this.headers })
.pipe(map((response) => response.json()));
}
apagarCategoria(id: number): Observable<any> {
return this.http.delete(`${this.url}/company-types/${id}`, { headers: this.headers })
.pipe(map((response) => response.json()));
}
atualizarCategoria(categoria: Tipo): Observable<any> {
return this.http.put(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
.pipe(map((response) => response.json()));
}
salvarCategoria(categoria: Tipo): Observable<any> {
return this.http.put(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
.pipe(map((response) => response.json()));
}
vincularEmpresaUser(empresa: EmpresaUsuario): Observable<Retorno<EmpresaUsuario>> {
return this.http.post(`${this.url}/company-users/associar`, JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<EmpresaUsuario>(response.json())));
}
adminBuscarTodos(page: number, size: number, sort: string, approved: boolean, pending: boolean, blocked: boolean,
denied: boolean, deleted: boolean, nome: string, tipo: number): Observable<Retorno<Array<Empresa>>> {
const params: URLSearchParams = new URLSearchParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
if (approved) {
params.set('approved', 'true');
}
if (pending) {
params.set('pending', pending.toString());
}
if (blocked) {
params.set('blocked', blocked.toString());
}
if (denied) {
params.set('denied', denied.toString());
}
if (deleted) {
params.set('deleted', deleted.toString());
}
if (nome) {
params.set('nome', nome);
}
if (tipo) {
params.set('typeId', tipo.toString());
}
return this.http.get(`${this.url}/companies`, { headers: this.headers, search: params.toString() })
.pipe(map((response) => new Retorno<Array<Empresa>>(response.json())));
}
deletarEmpresa(id: number): Observable<Retorno<any>> {
return this.http.delete(`${this.url}/companies/${id}`, { headers: this.headers })
.pipe(map((response) => new Retorno<any>(response.json())));
}
uploadXLSX(file: File) {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(`${this.url}/companies/xls/`, formData, { headers: this.headersFile })
.pipe(map((response) => response.json()));
}
buscarEmpresaCNPJ8(cnpj: string): Observable<Retorno<EmpresaUsuario>> {
return this.http.get(`${this.url}/companies/cnpj8/${cnpj}`, { headers: this.headers })
.pipe(map((response) => new Retorno<EmpresaUsuario>(response.json())));
}
adminBuscarEmpresasPorTipo(page: number, size: number, sort: string, tipos: Array<number>,
id: number, nome: string): Observable<Retorno<Empresa>> {
let t = null;
try {
t = tipos.join(',');
} catch {
t = tipos;
}
let url = `${this.url}/companies/buscar-tipo?page=${page}&size=${size}&sort=${sort}&tipos=${t}`;
if (nome) {
url = url + `&nome=${nome}`;
}
if (id) {
url = url + `&id=${id}`;
}
return this.http.get(url, { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
public buscarResumoFornecedor(referencia: string): Observable<Retorno<ResumoFornecedor>> {
return this.http.get(`${this.url}/company-dashboard/resumo/fornecedor/referencia/${referencia}`, { headers: this.headers })
.pipe(map((response) => new Retorno<ResumoFornecedor>(response.json())));
}
public buscarResumoAgencia(): Observable<Retorno<ResumoAgencia>> {
return this.http.get(`${this.url}/company-dashboard/resumo/agencia`, { headers: this.headers })
.pipe(map((response) => new Retorno<ResumoAgencia>(response.json())));
}
public buscarBarraCamposPreenchidos(): Observable<Retorno<number>> {
return this.http.get(`${this.url}/company-dashboard/barra-campos`, { headers: this.headers })
.pipe(map((response) => new Retorno<number>(response.json())));
}
public salvarLocalizacoes(id: number, locais: Array<ApiLoacalizacaoCidadecp>):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post(`${this.url}/company-localizacao/salvar/${id}`, JSON.stringify(locais), { headers: this.headers })
.pipe(map((response) => new Retorno<Array<ApiLoacalizacaoCidadecp>>(response.json())));
}
public removerLocalizacao(id: number, local: ApiLoacalizacaoCidadecp):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post(`${this.url}/company-localizacao/remover/${id}`, JSON.stringify(local), { headers: this.headers })
.pipe(map((response) => new Retorno<Array<ApiLoacalizacaoCidadecp>>(response.json())));
}
public adminBuscarLocalizacoes(page: number, size: number, sort: string): Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
const params: URLSearchParams = new URLSearchParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
return this.http.get(`${this.url}/company-localizacao/admin-filtrar`, { headers: this.headers, search: params.toString() })
.pipe(map((response) => new Retorno<Array<ApiLoacalizacaoCidadecp>>(response.json())));
}
public buscarLocalizacoes(texto: string): Observable<any> {
const params: URLSearchParams = new URLSearchParams();
params.set('texto', texto.toString());
return this.http.get(`${this.url}/company-localizacao`, { headers: this.headers, search: params.toString() })
.pipe(map((response) => response.json().response));
}
private resolveUrlSearchBug(): boolean {
const url = window.location.pathname.split("/");
if (url[1] !== 'empresas') {
return true;
}
}
}
在 (HttpClient) 之后
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Environment } from '../app.component';
//my components imports
@Injectable()
export class CompanyService implements OnDestroy {
private url = Environment.origin;
private urlMainSearch = Environment.MAIN_SEARCH;
private urlSearchAll = Environment.SEARCH_ALL;
private headers = new HttpHeaders({
'Accept': 'application/cp+json',
'Content-Type': 'application/json'
});
private headersFile = new HttpHeaders({
'Accept': 'application/cp+json',
'Content-Type': 'multipart/form-data; boundary=something'
});
constructor(private http: HttpClient) { }
ngOnDestroy() {
delete this.http;
}
buscarEmpresas(pesquisa: string): Observable<any> {
return this.http.get<any>(`${this.url}/companies/${pesquisa}/search`, { headers: this.headers })
}
buscarEmpresasCache(pesquisa: string): Observable<any> {
return this.http.get<any>(`${this.url}/companies/search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
}
buscarEmpresasMicroServico(pesquisa: string): Observable<any> {
return this.http.get<any>(`${this.urlMainSearch}/main-search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
}
getEmpresa(id: number): Observable<Retorno<Empresa>> {
return this.http.get<Retorno<Empresa>>(`${this.url}/companies/${id}`, { headers: this.headers })
}
getEmpresaByUrlLink(urlLink: string): Observable<Retorno<Empresa>> {
return this.http.get<Retorno<Empresa>>(`${this.url}/companies/link/${urlLink}`, { headers: this.headers })
}
getEmpresaRatings(id: number): Observable<Retorno<Rating>> {
return this.http.get<Retorno<Rating>>(`${this.url}/companies/${id}/ratings`, { headers: this.headers })
}
getOperadora(): Observable<Array<Empresa>> {
return this.http.get<Array<Empresa>>(`${this.url}/companies/search/operadora/10/1`, { headers: this.headers })
}
getTopEmpresas(type: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get<Retorno<Array<Empresa>>>(`${this.url}/companies/top?type=${type}`, { headers: this.headers })
}
buscarEmpresasPorTipo(tipo: number, pagina: number, tags: Array<number>, continentes: Array<number>,
paises: Array<number>, cidades: Array<number>): Observable<Retorno<Array<EmpresaRating>>> {
// if(!this.resolveUrlSearchBug()) {
let url = `${this.url}/companies/searchtype?number=25&page=${pagina}&type=${tipo}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (continentes && continentes.length > 0) {
const continente = `&continentes=${continentes.join(',')}`;
url = url + continente;
}
if (paises && paises.length > 0) {
const pais = `&paises=${paises.join(',')}`;
url = url + pais;
}
if (cidades && cidades.length > 0) {
const cidade = `&cidades=${cidades.join(',')}`;
url = url + cidade;
}
return this.http.get<Retorno<Array<EmpresaRating>>>(url, { headers: this.headers })
// }
}
buscarTodasEmpresas(pagina: number, texto: string, tipos: Array<number>, tags: Array<number>, localizacoes: Array<number>):
Observable<Retorno<RankingTodasEmpresas>> {
let url = `${this.urlSearchAll}/company-search-all?texto=${texto}&limit=25&offset=${pagina}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (localizacoes && localizacoes.length > 0) {
const localizacao = `&localizacoes=${localizacoes.join(',')}`;
url = url + localizacao;
}
if (tipos && tipos.length > 0) {
const tipo = `&tipos=${tipos.join(',')}`;
url = url + tipo;
}
return this.http.get<Retorno<RankingTodasEmpresas>>(url, { headers: this.headers })
}
buscarEmpresasSimilares(tipo: number, idEmpresaPesquisada: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get<Retorno<Array<Empresa>>>(`${this.url}/companies/random-searchtype?type=${tipo}&idEmpresaPesquisada=${idEmpresaPesquisada}`, { headers: this.headers })
}
buscarMenuTags(tipo: number): Observable<Retorno<SuperMenu>> {
// console.log(this.resolveUrlSearchBug());
// if(!this.resolveUrlSearchBug()) {
// console.log('Chamando service.........');
return this.http.get<Retorno<SuperMenu>>(`${this.url}/companies/searchtype/filtro?type=${tipo}`, { headers: this.headers })
// }
}
cadastrarEmpresa(empresa: Empresa, isByCadFornecedor: boolean = false): Observable<Retorno<Empresa>> {
return this.http.post<Retorno<Empresa>>(`${this.url}/companies?isByCadFornecedor=${isByCadFornecedor}`,
JSON.stringify(empresa), { headers: this.headers })
}
cadastrarEmpresaPreCadastro(preCadastro: EmpresaPreCadastro): Observable<Retorno<Empresa>> {
return this.http.post<Retorno<Empresa>>(`${this.url}/companies/pre-cadastro`,
JSON.stringify(preCadastro), { headers: this.headers })
}
adminCadastrarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.post<Retorno<Empresa>>(`${this.url}/companies/admin`, JSON.stringify(empresa), { headers: this.headers })
}
alterarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.put<Retorno<Empresa>>(`${this.url}/companies`, JSON.stringify(empresa), { headers: this.headers })
}
buscarTiposEmpresa(): Observable<Retorno<Array<Tipo>>> {
return this.http.get<Retorno<Array<Tipo>>>(`${this.url}/categories`, { headers: this.headers })
}
buscarTipoEmpresa(tipo: number): Observable<Retorno<Tipo>> {
return this.http.get<Retorno<Tipo>>(`${this.url}/company-types/${tipo}`, { headers: this.headers })
}
buscarTipoEmpresaPorUrlLink(urlLink: string): Observable<Retorno<Tipo>> {
if (this.http) {
return this.http.get<Retorno<Tipo>>(`${this.url}/company-types/link/${urlLink}`, { headers: this.headers })
}
}
atualizarStatus(codigo: number): Observable<any> {
return this.http.put<any>(`${this.url}/company-status`, JSON.stringify(codigo), { headers: this.headers })
}
apagarCategoria(id: number): Observable<any> {
return this.http.delete<any>(`${this.url}/company-types/${id}`, { headers: this.headers })
}
atualizarCategoria(categoria: Tipo): Observable<any> {
return this.http.put<any>(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
}
salvarCategoria(categoria: Tipo): Observable<any> {
return this.http.put<any>(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
}
vincularEmpresaUser(empresa: EmpresaUsuario): Observable<Retorno<EmpresaUsuario>> {
return this.http.post<Retorno<EmpresaUsuario>>(`${this.url}/company-users/associar`, JSON.stringify(empresa), { headers: this.headers })
}
adminBuscarTodos(page: number, size: number, sort: string, approved: boolean, pending: boolean, blocked: boolean,
denied: boolean, deleted: boolean, nome: string, tipo: number): Observable<Retorno<Array<Empresa>>> {
const params: HttpParams = new HttpParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
if (approved) {
params.set('approved', 'true');
}
if (pending) {
params.set('pending', pending.toString());
}
if (blocked) {
params.set('blocked', blocked.toString());
}
if (denied) {
params.set('denied', denied.toString());
}
if (deleted) {
params.set('deleted', deleted.toString());
}
if (nome) {
params.set('nome', nome);
}
if (tipo) {
params.set('typeId', tipo.toString());
}
return this.http.get<Retorno<Array<Empresa>>>(`${this.url}/companies`, { headers: this.headers, params })
}
deletarEmpresa(id: number): Observable<Retorno<any>> {
return this.http.delete<any>(`${this.url}/companies/${id}`, { headers: this.headers })
}
uploadXLSX(file: File) {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(`${this.url}/companies/xls/`, formData, { headers: this.headersFile })
}
buscarEmpresaCNPJ8(cnpj: string): Observable<Retorno<EmpresaUsuario>> {
return this.http.get<Retorno<EmpresaUsuario>>(`${this.url}/companies/cnpj8/${cnpj}`, { headers: this.headers })
}
adminBuscarEmpresasPorTipo(page: number, size: number, sort: string, tipos: Array<number>,
id: number, nome: string): Observable<Retorno<Empresa>> {
let t = null;
try {
t = tipos.join(',');
} catch {
t = tipos;
}
let url = `${this.url}/companies/buscar-tipo?page=${page}&size=${size}&sort=${sort}&tipos=${t}`;
if (nome) {
url = url + `&nome=${nome}`;
}
if (id) {
url = url + `&id=${id}`;
}
return this.http.get<Retorno<Empresa>>(url, { headers: this.headers })
}
public buscarResumoFornecedor(referencia: string): Observable<Retorno<ResumoFornecedor>> {
return this.http.get<Retorno<ResumoFornecedor>>(`${this.url}/company-dashboard/resumo/fornecedor/referencia/${referencia}`, { headers: this.headers })
}
public buscarResumoAgencia(): Observable<Retorno<ResumoAgencia>> {
return this.http.get<Retorno<ResumoAgencia>>(`${this.url}/company-dashboard/resumo/agencia`, { headers: this.headers })
}
public buscarBarraCamposPreenchidos(): Observable<Retorno<number>> {
return this.http.get<Retorno<number>>(`${this.url}/company-dashboard/barra-campos`, { headers: this.headers })
}
public salvarLocalizacoes(id: number, locais: Array<ApiLoacalizacaoCidadecp>):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post<Retorno<Array<ApiLoacalizacaoCidadecp>>>(`${this.url}/company-localizacao/salvar/${id}`, JSON.stringify(locais), { headers: this.headers })
}
public removerLocalizacao(id: number, local: ApiLoacalizacaoCidadecp):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post<Retorno<Array<ApiLoacalizacaoCidadecp>>>(`${this.url}/company-localizacao/remover/${id}`, JSON.stringify(local), { headers: this.headers })
}
public adminBuscarLocalizacoes(page: number, size: number, sort: string): Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
const params: HttpParams = new HttpParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
return this.http.get<Retorno<Array<ApiLoacalizacaoCidadecp>>>(`${this.url}/company-localizacao/admin-filtrar`, { headers: this.headers, params })
}
public buscarLocalizacoes(texto: string): Observable<any> {
const params: HttpParams = new HttpParams();
params.set('texto', texto.toString());
return this.http.get<any>(`${this.url}/company-localizacao`, { headers: this.headers, params })
}
private resolveUrlSearchBug(): boolean {
const url = window.location.pathname.split("/");
if (url[1] !== 'empresas') {
return true;
}
}
}
我假设变量 this.http
的类型是 HttpClient
。 HttpClient.get()
的类型定义指出 options
参数有一个可选的 属性 params
,类型为:
params?: HttpParams | { [param: string]: string | string[]; };
它不能是单个 string
(这就是 params.toString()
returns)。它是 strings
的 key-value 对象或 HttpParams
对象。
您可以直接传递 params
变量,因为它的类型是 HttpParams
.
而不是
{ headers: this.headers, params: params.toString() }
随心所欲
{ headers: this.headers, params }
但是在这两种情况下 params
不总是空的吗?您初始化一个空对象并且不向其添加任何内容(除非您省略了该部分)。
编辑:
看到你的完整代码后,我可以解释参数为空的情况。
在 URLSearchParams
class 上,set()
方法是一个 void
方法,它改变了对象,returns 没有。在原始代码中,他们所做的是创建一个空对象,在其上设置一堆值,然后将其转换为字符串。 (我问了关于它是空的问题,因为带有 params.set()
的部分不是您的示例代码的一部分)。
(method) URLSearchParams.set(name: string, value: string): void
Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
HttpParams
class 的工作方式不同。它不是使用您设置的值更新自身,而是 returns 一个新实例。
(method) HttpParams.set(param: string, value: string): HttpParams
Replaces the value for a parameter.
@param param — The parameter name.
@param value — The new value.
@return — A new body with the new value.
但是您没有对返回值执行任何操作,因为原始代码是在期望 void
方法的情况下构建的。每次设置某些内容时,您都需要将 params
的值更改为返回值。将每个 const params
更改为 let params
以便我们可以覆盖它。然后用 params = params.set()
替换对 params.set()
的所有调用。像这样:
let params: HttpParams = new HttpParams();
params = params.set('page', page.toString());
params = params.set('size', size.toString());
params = params.set('sort', sort);
我正在尝试将 Angular8 上的 service.ts 的 Http 更新为 HttpClient。
我已经为 HttpClient 和 HttpHeaders 更改了 Http 和 Headers,并且删除了 '.pipe(map((response) => response.json().response ));'.选项 search:params.toString() 在 HttpParams 上不起作用,按照建议,我已更改为仅参数。
但是请求没有正常工作:(
之前(Http)
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Http, Headers, Jsonp } from '@angular/http';
import { Environment } from '../app.component';
//my components imports
@Injectable()
export class CompanyService implements OnDestroy {
private url = Environment.origin;
private urlMainSearch = Environment.MAIN_SEARCH;
private urlSearchAll = Environment.SEARCH_ALL;
private headers = new Headers({
'Accept': 'application/cp+json',
'Content-Type': 'application/json'
});
private headersFile = new Headers({
'Accept': 'application/cp+json',
'Content-Type': 'multipart/form-data; boundary=something'
});
constructor(private http: Http,
private jsonp: Jsonp) { }
ngOnDestroy() {
delete this.http;
}
buscarEmpresas(pesquisa: string): Observable<any> {
return this.http.get(`${this.url}/companies/${pesquisa}/search`, { headers: this.headers })
.pipe(map((response) => response.json().response));
}
buscarEmpresasCache(pesquisa: string): Observable<any> {
return this.http.get(`${this.url}/companies/search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
.pipe(map((response) => response.json().response));
}
buscarEmpresasMicroServico(pesquisa: string): Observable<any> {
return this.http.get(`${this.urlMainSearch}/main-search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
.pipe(map((response) => response.json().response));
}
getEmpresa(id: number): Observable<Retorno<Empresa>> {
return this.http.get(`${this.url}/companies/${id}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
getEmpresaByUrlLink(urlLink: string): Observable<Retorno<Empresa>> {
return this.http.get(`${this.url}/companies/link/${urlLink}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
getEmpresaRatings(id: number): Observable<Retorno<Rating>> {
return this.http.get(`${this.url}/companies/${id}/ratings`, { headers: this.headers })
.pipe(map((response) => new Retorno<Rating>(response.json())));
}
getOperadora(): Observable<Array<Empresa>> {
return this.http.get(`${this.url}/companies/search/operadora/10/1`, { headers: this.headers })
.pipe(map((response) => response.json().map(empresa => new Empresa(empresa))));
}
getTopEmpresas(type: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get(`${this.url}/companies/top?type=${type}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Array<Empresa>>(response.json())));
}
buscarEmpresasPorTipo(tipo: number, pagina: number, tags: Array<number>, continentes: Array<number>,
paises: Array<number>, cidades: Array<number>): Observable<Retorno<Array<EmpresaRating>>> {
// if(!this.resolveUrlSearchBug()) {
let url = `${this.url}/companies/searchtype?number=25&page=${pagina}&type=${tipo}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (continentes && continentes.length > 0) {
const continente = `&continentes=${continentes.join(',')}`;
url = url + continente;
}
if (paises && paises.length > 0) {
const pais = `&paises=${paises.join(',')}`;
url = url + pais;
}
if (cidades && cidades.length > 0) {
const cidade = `&cidades=${cidades.join(',')}`;
url = url + cidade;
}
return this.http.get(url, { headers: this.headers })
.pipe(map((response) => new Retorno<Array<EmpresaRating>>(response.json())));
// }
}
buscarTodasEmpresas(pagina: number, texto: string, tipos: Array<number>, tags: Array<number>, localizacoes: Array<number>):
Observable<Retorno<RankingTodasEmpresas>> {
let url = `${this.urlSearchAll}/company-search-all?texto=${texto}&limit=25&offset=${pagina}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (localizacoes && localizacoes.length > 0) {
const localizacao = `&localizacoes=${localizacoes.join(',')}`;
url = url + localizacao;
}
if (tipos && tipos.length > 0) {
const tipo = `&tipos=${tipos.join(',')}`;
url = url + tipo;
}
return this.http.get(url, { headers: this.headers })
.pipe(map((response) => new Retorno<RankingTodasEmpresas>(response.json())));
}
buscarEmpresasSimilares(tipo: number, idEmpresaPesquisada: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get(`${this.url}/companies/random-searchtype?type=${tipo}&idEmpresaPesquisada=${idEmpresaPesquisada}`,
{ headers: this.headers })
.pipe(map((response) => new Retorno<Array<Empresa>>(response.json())));
}
buscarMenuTags(tipo: number): Observable<Retorno<SuperMenu>> {
// console.log(this.resolveUrlSearchBug());
// if(!this.resolveUrlSearchBug()) {
// console.log('Chamando service.........');
return this.http.get(`${this.url}/companies/searchtype/filtro?type=${tipo}`, { headers: this.headers })
.pipe(map((response) => new Retorno<SuperMenu>(response.json())));
// }
}
cadastrarEmpresa(empresa: Empresa, isByCadFornecedor: boolean = false): Observable<Retorno<Empresa>> {
return this.http.post(`${this.url}/companies?isByCadFornecedor=${isByCadFornecedor}`,
JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
cadastrarEmpresaPreCadastro(preCadastro: EmpresaPreCadastro): Observable<Retorno<Empresa>> {
return this.http.post(`${this.url}/companies/pre-cadastro`,
JSON.stringify(preCadastro), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
adminCadastrarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.post(`${this.url}/companies/admin`, JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
alterarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.put(`${this.url}/companies`, JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
buscarTiposEmpresa(): Observable<Retorno<Array<Tipo>>> {
return this.http.get(`${this.url}/categories`, { headers: this.headers })
.pipe(map((response) => new Retorno<Array<Tipo>>(response.json())));
}
buscarTipoEmpresa(tipo: number): Observable<Retorno<Tipo>> {
return this.http.get(`${this.url}/company-types/${tipo}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Tipo>(response.json())));
}
buscarTipoEmpresaPorUrlLink(urlLink: string): Observable<Retorno<Tipo>> {
if (this.http) {
return this.http.get(`${this.url}/company-types/link/${urlLink}`, { headers: this.headers })
.pipe(map((response) => new Retorno<Tipo>(response.json())));
}
}
atualizarStatus(codigo: number): Observable<any> {
return this.http.put(`${this.url}/company-status`, JSON.stringify(codigo), { headers: this.headers })
.pipe(map((response) => response.json()));
}
apagarCategoria(id: number): Observable<any> {
return this.http.delete(`${this.url}/company-types/${id}`, { headers: this.headers })
.pipe(map((response) => response.json()));
}
atualizarCategoria(categoria: Tipo): Observable<any> {
return this.http.put(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
.pipe(map((response) => response.json()));
}
salvarCategoria(categoria: Tipo): Observable<any> {
return this.http.put(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
.pipe(map((response) => response.json()));
}
vincularEmpresaUser(empresa: EmpresaUsuario): Observable<Retorno<EmpresaUsuario>> {
return this.http.post(`${this.url}/company-users/associar`, JSON.stringify(empresa), { headers: this.headers })
.pipe(map((response) => new Retorno<EmpresaUsuario>(response.json())));
}
adminBuscarTodos(page: number, size: number, sort: string, approved: boolean, pending: boolean, blocked: boolean,
denied: boolean, deleted: boolean, nome: string, tipo: number): Observable<Retorno<Array<Empresa>>> {
const params: URLSearchParams = new URLSearchParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
if (approved) {
params.set('approved', 'true');
}
if (pending) {
params.set('pending', pending.toString());
}
if (blocked) {
params.set('blocked', blocked.toString());
}
if (denied) {
params.set('denied', denied.toString());
}
if (deleted) {
params.set('deleted', deleted.toString());
}
if (nome) {
params.set('nome', nome);
}
if (tipo) {
params.set('typeId', tipo.toString());
}
return this.http.get(`${this.url}/companies`, { headers: this.headers, search: params.toString() })
.pipe(map((response) => new Retorno<Array<Empresa>>(response.json())));
}
deletarEmpresa(id: number): Observable<Retorno<any>> {
return this.http.delete(`${this.url}/companies/${id}`, { headers: this.headers })
.pipe(map((response) => new Retorno<any>(response.json())));
}
uploadXLSX(file: File) {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(`${this.url}/companies/xls/`, formData, { headers: this.headersFile })
.pipe(map((response) => response.json()));
}
buscarEmpresaCNPJ8(cnpj: string): Observable<Retorno<EmpresaUsuario>> {
return this.http.get(`${this.url}/companies/cnpj8/${cnpj}`, { headers: this.headers })
.pipe(map((response) => new Retorno<EmpresaUsuario>(response.json())));
}
adminBuscarEmpresasPorTipo(page: number, size: number, sort: string, tipos: Array<number>,
id: number, nome: string): Observable<Retorno<Empresa>> {
let t = null;
try {
t = tipos.join(',');
} catch {
t = tipos;
}
let url = `${this.url}/companies/buscar-tipo?page=${page}&size=${size}&sort=${sort}&tipos=${t}`;
if (nome) {
url = url + `&nome=${nome}`;
}
if (id) {
url = url + `&id=${id}`;
}
return this.http.get(url, { headers: this.headers })
.pipe(map((response) => new Retorno<Empresa>(response.json())));
}
public buscarResumoFornecedor(referencia: string): Observable<Retorno<ResumoFornecedor>> {
return this.http.get(`${this.url}/company-dashboard/resumo/fornecedor/referencia/${referencia}`, { headers: this.headers })
.pipe(map((response) => new Retorno<ResumoFornecedor>(response.json())));
}
public buscarResumoAgencia(): Observable<Retorno<ResumoAgencia>> {
return this.http.get(`${this.url}/company-dashboard/resumo/agencia`, { headers: this.headers })
.pipe(map((response) => new Retorno<ResumoAgencia>(response.json())));
}
public buscarBarraCamposPreenchidos(): Observable<Retorno<number>> {
return this.http.get(`${this.url}/company-dashboard/barra-campos`, { headers: this.headers })
.pipe(map((response) => new Retorno<number>(response.json())));
}
public salvarLocalizacoes(id: number, locais: Array<ApiLoacalizacaoCidadecp>):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post(`${this.url}/company-localizacao/salvar/${id}`, JSON.stringify(locais), { headers: this.headers })
.pipe(map((response) => new Retorno<Array<ApiLoacalizacaoCidadecp>>(response.json())));
}
public removerLocalizacao(id: number, local: ApiLoacalizacaoCidadecp):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post(`${this.url}/company-localizacao/remover/${id}`, JSON.stringify(local), { headers: this.headers })
.pipe(map((response) => new Retorno<Array<ApiLoacalizacaoCidadecp>>(response.json())));
}
public adminBuscarLocalizacoes(page: number, size: number, sort: string): Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
const params: URLSearchParams = new URLSearchParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
return this.http.get(`${this.url}/company-localizacao/admin-filtrar`, { headers: this.headers, search: params.toString() })
.pipe(map((response) => new Retorno<Array<ApiLoacalizacaoCidadecp>>(response.json())));
}
public buscarLocalizacoes(texto: string): Observable<any> {
const params: URLSearchParams = new URLSearchParams();
params.set('texto', texto.toString());
return this.http.get(`${this.url}/company-localizacao`, { headers: this.headers, search: params.toString() })
.pipe(map((response) => response.json().response));
}
private resolveUrlSearchBug(): boolean {
const url = window.location.pathname.split("/");
if (url[1] !== 'empresas') {
return true;
}
}
}
在 (HttpClient) 之后
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Environment } from '../app.component';
//my components imports
@Injectable()
export class CompanyService implements OnDestroy {
private url = Environment.origin;
private urlMainSearch = Environment.MAIN_SEARCH;
private urlSearchAll = Environment.SEARCH_ALL;
private headers = new HttpHeaders({
'Accept': 'application/cp+json',
'Content-Type': 'application/json'
});
private headersFile = new HttpHeaders({
'Accept': 'application/cp+json',
'Content-Type': 'multipart/form-data; boundary=something'
});
constructor(private http: HttpClient) { }
ngOnDestroy() {
delete this.http;
}
buscarEmpresas(pesquisa: string): Observable<any> {
return this.http.get<any>(`${this.url}/companies/${pesquisa}/search`, { headers: this.headers })
}
buscarEmpresasCache(pesquisa: string): Observable<any> {
return this.http.get<any>(`${this.url}/companies/search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
}
buscarEmpresasMicroServico(pesquisa: string): Observable<any> {
return this.http.get<any>(`${this.urlMainSearch}/main-search?texto=${StringUtils.unaccent(pesquisa)}`, { headers: this.headers })
}
getEmpresa(id: number): Observable<Retorno<Empresa>> {
return this.http.get<Retorno<Empresa>>(`${this.url}/companies/${id}`, { headers: this.headers })
}
getEmpresaByUrlLink(urlLink: string): Observable<Retorno<Empresa>> {
return this.http.get<Retorno<Empresa>>(`${this.url}/companies/link/${urlLink}`, { headers: this.headers })
}
getEmpresaRatings(id: number): Observable<Retorno<Rating>> {
return this.http.get<Retorno<Rating>>(`${this.url}/companies/${id}/ratings`, { headers: this.headers })
}
getOperadora(): Observable<Array<Empresa>> {
return this.http.get<Array<Empresa>>(`${this.url}/companies/search/operadora/10/1`, { headers: this.headers })
}
getTopEmpresas(type: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get<Retorno<Array<Empresa>>>(`${this.url}/companies/top?type=${type}`, { headers: this.headers })
}
buscarEmpresasPorTipo(tipo: number, pagina: number, tags: Array<number>, continentes: Array<number>,
paises: Array<number>, cidades: Array<number>): Observable<Retorno<Array<EmpresaRating>>> {
// if(!this.resolveUrlSearchBug()) {
let url = `${this.url}/companies/searchtype?number=25&page=${pagina}&type=${tipo}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (continentes && continentes.length > 0) {
const continente = `&continentes=${continentes.join(',')}`;
url = url + continente;
}
if (paises && paises.length > 0) {
const pais = `&paises=${paises.join(',')}`;
url = url + pais;
}
if (cidades && cidades.length > 0) {
const cidade = `&cidades=${cidades.join(',')}`;
url = url + cidade;
}
return this.http.get<Retorno<Array<EmpresaRating>>>(url, { headers: this.headers })
// }
}
buscarTodasEmpresas(pagina: number, texto: string, tipos: Array<number>, tags: Array<number>, localizacoes: Array<number>):
Observable<Retorno<RankingTodasEmpresas>> {
let url = `${this.urlSearchAll}/company-search-all?texto=${texto}&limit=25&offset=${pagina}`;
if (tags && tags.length > 0) {
const tag = `&tags=${tags.join(',')}`;
url = url + tag;
}
if (localizacoes && localizacoes.length > 0) {
const localizacao = `&localizacoes=${localizacoes.join(',')}`;
url = url + localizacao;
}
if (tipos && tipos.length > 0) {
const tipo = `&tipos=${tipos.join(',')}`;
url = url + tipo;
}
return this.http.get<Retorno<RankingTodasEmpresas>>(url, { headers: this.headers })
}
buscarEmpresasSimilares(tipo: number, idEmpresaPesquisada: number): Observable<Retorno<Array<Empresa>>> {
return this.http.get<Retorno<Array<Empresa>>>(`${this.url}/companies/random-searchtype?type=${tipo}&idEmpresaPesquisada=${idEmpresaPesquisada}`, { headers: this.headers })
}
buscarMenuTags(tipo: number): Observable<Retorno<SuperMenu>> {
// console.log(this.resolveUrlSearchBug());
// if(!this.resolveUrlSearchBug()) {
// console.log('Chamando service.........');
return this.http.get<Retorno<SuperMenu>>(`${this.url}/companies/searchtype/filtro?type=${tipo}`, { headers: this.headers })
// }
}
cadastrarEmpresa(empresa: Empresa, isByCadFornecedor: boolean = false): Observable<Retorno<Empresa>> {
return this.http.post<Retorno<Empresa>>(`${this.url}/companies?isByCadFornecedor=${isByCadFornecedor}`,
JSON.stringify(empresa), { headers: this.headers })
}
cadastrarEmpresaPreCadastro(preCadastro: EmpresaPreCadastro): Observable<Retorno<Empresa>> {
return this.http.post<Retorno<Empresa>>(`${this.url}/companies/pre-cadastro`,
JSON.stringify(preCadastro), { headers: this.headers })
}
adminCadastrarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.post<Retorno<Empresa>>(`${this.url}/companies/admin`, JSON.stringify(empresa), { headers: this.headers })
}
alterarEmpresa(empresa: Empresa): Observable<Retorno<Empresa>> {
return this.http.put<Retorno<Empresa>>(`${this.url}/companies`, JSON.stringify(empresa), { headers: this.headers })
}
buscarTiposEmpresa(): Observable<Retorno<Array<Tipo>>> {
return this.http.get<Retorno<Array<Tipo>>>(`${this.url}/categories`, { headers: this.headers })
}
buscarTipoEmpresa(tipo: number): Observable<Retorno<Tipo>> {
return this.http.get<Retorno<Tipo>>(`${this.url}/company-types/${tipo}`, { headers: this.headers })
}
buscarTipoEmpresaPorUrlLink(urlLink: string): Observable<Retorno<Tipo>> {
if (this.http) {
return this.http.get<Retorno<Tipo>>(`${this.url}/company-types/link/${urlLink}`, { headers: this.headers })
}
}
atualizarStatus(codigo: number): Observable<any> {
return this.http.put<any>(`${this.url}/company-status`, JSON.stringify(codigo), { headers: this.headers })
}
apagarCategoria(id: number): Observable<any> {
return this.http.delete<any>(`${this.url}/company-types/${id}`, { headers: this.headers })
}
atualizarCategoria(categoria: Tipo): Observable<any> {
return this.http.put<any>(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
}
salvarCategoria(categoria: Tipo): Observable<any> {
return this.http.put<any>(`${this.url}/company-types`, JSON.stringify(categoria), { headers: this.headers })
}
vincularEmpresaUser(empresa: EmpresaUsuario): Observable<Retorno<EmpresaUsuario>> {
return this.http.post<Retorno<EmpresaUsuario>>(`${this.url}/company-users/associar`, JSON.stringify(empresa), { headers: this.headers })
}
adminBuscarTodos(page: number, size: number, sort: string, approved: boolean, pending: boolean, blocked: boolean,
denied: boolean, deleted: boolean, nome: string, tipo: number): Observable<Retorno<Array<Empresa>>> {
const params: HttpParams = new HttpParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
if (approved) {
params.set('approved', 'true');
}
if (pending) {
params.set('pending', pending.toString());
}
if (blocked) {
params.set('blocked', blocked.toString());
}
if (denied) {
params.set('denied', denied.toString());
}
if (deleted) {
params.set('deleted', deleted.toString());
}
if (nome) {
params.set('nome', nome);
}
if (tipo) {
params.set('typeId', tipo.toString());
}
return this.http.get<Retorno<Array<Empresa>>>(`${this.url}/companies`, { headers: this.headers, params })
}
deletarEmpresa(id: number): Observable<Retorno<any>> {
return this.http.delete<any>(`${this.url}/companies/${id}`, { headers: this.headers })
}
uploadXLSX(file: File) {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(`${this.url}/companies/xls/`, formData, { headers: this.headersFile })
}
buscarEmpresaCNPJ8(cnpj: string): Observable<Retorno<EmpresaUsuario>> {
return this.http.get<Retorno<EmpresaUsuario>>(`${this.url}/companies/cnpj8/${cnpj}`, { headers: this.headers })
}
adminBuscarEmpresasPorTipo(page: number, size: number, sort: string, tipos: Array<number>,
id: number, nome: string): Observable<Retorno<Empresa>> {
let t = null;
try {
t = tipos.join(',');
} catch {
t = tipos;
}
let url = `${this.url}/companies/buscar-tipo?page=${page}&size=${size}&sort=${sort}&tipos=${t}`;
if (nome) {
url = url + `&nome=${nome}`;
}
if (id) {
url = url + `&id=${id}`;
}
return this.http.get<Retorno<Empresa>>(url, { headers: this.headers })
}
public buscarResumoFornecedor(referencia: string): Observable<Retorno<ResumoFornecedor>> {
return this.http.get<Retorno<ResumoFornecedor>>(`${this.url}/company-dashboard/resumo/fornecedor/referencia/${referencia}`, { headers: this.headers })
}
public buscarResumoAgencia(): Observable<Retorno<ResumoAgencia>> {
return this.http.get<Retorno<ResumoAgencia>>(`${this.url}/company-dashboard/resumo/agencia`, { headers: this.headers })
}
public buscarBarraCamposPreenchidos(): Observable<Retorno<number>> {
return this.http.get<Retorno<number>>(`${this.url}/company-dashboard/barra-campos`, { headers: this.headers })
}
public salvarLocalizacoes(id: number, locais: Array<ApiLoacalizacaoCidadecp>):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post<Retorno<Array<ApiLoacalizacaoCidadecp>>>(`${this.url}/company-localizacao/salvar/${id}`, JSON.stringify(locais), { headers: this.headers })
}
public removerLocalizacao(id: number, local: ApiLoacalizacaoCidadecp):
Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
return this.http.post<Retorno<Array<ApiLoacalizacaoCidadecp>>>(`${this.url}/company-localizacao/remover/${id}`, JSON.stringify(local), { headers: this.headers })
}
public adminBuscarLocalizacoes(page: number, size: number, sort: string): Observable<Retorno<Array<ApiLoacalizacaoCidadecp>>> {
const params: HttpParams = new HttpParams();
params.set('page', page.toString());
params.set('size', size.toString());
params.set('sort', sort);
return this.http.get<Retorno<Array<ApiLoacalizacaoCidadecp>>>(`${this.url}/company-localizacao/admin-filtrar`, { headers: this.headers, params })
}
public buscarLocalizacoes(texto: string): Observable<any> {
const params: HttpParams = new HttpParams();
params.set('texto', texto.toString());
return this.http.get<any>(`${this.url}/company-localizacao`, { headers: this.headers, params })
}
private resolveUrlSearchBug(): boolean {
const url = window.location.pathname.split("/");
if (url[1] !== 'empresas') {
return true;
}
}
}
我假设变量 this.http
的类型是 HttpClient
。 HttpClient.get()
的类型定义指出 options
参数有一个可选的 属性 params
,类型为:
params?: HttpParams | { [param: string]: string | string[]; };
它不能是单个 string
(这就是 params.toString()
returns)。它是 strings
的 key-value 对象或 HttpParams
对象。
您可以直接传递 params
变量,因为它的类型是 HttpParams
.
而不是
{ headers: this.headers, params: params.toString() }
随心所欲
{ headers: this.headers, params }
但是在这两种情况下 params
不总是空的吗?您初始化一个空对象并且不向其添加任何内容(除非您省略了该部分)。
编辑:
看到你的完整代码后,我可以解释参数为空的情况。
在 URLSearchParams
class 上,set()
方法是一个 void
方法,它改变了对象,returns 没有。在原始代码中,他们所做的是创建一个空对象,在其上设置一堆值,然后将其转换为字符串。 (我问了关于它是空的问题,因为带有 params.set()
的部分不是您的示例代码的一部分)。
(method) URLSearchParams.set(name: string, value: string): void
Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
HttpParams
class 的工作方式不同。它不是使用您设置的值更新自身,而是 returns 一个新实例。
(method) HttpParams.set(param: string, value: string): HttpParams
Replaces the value for a parameter.
@param param — The parameter name.
@param value — The new value.
@return — A new body with the new value.
但是您没有对返回值执行任何操作,因为原始代码是在期望 void
方法的情况下构建的。每次设置某些内容时,您都需要将 params
的值更改为返回值。将每个 const params
更改为 let params
以便我们可以覆盖它。然后用 params = params.set()
替换对 params.set()
的所有调用。像这样:
let params: HttpParams = new HttpParams();
params = params.set('page', page.toString());
params = params.set('size', size.toString());
params = params.set('sort', sort);