简体   繁体   中英

Convert URLSearchParams to HttpParams - Angular HttpClient

I am trying to update the Http to HttpClient from a service.ts on Angular8.

I have changed the Http and Headers for HttpClient and HttpHeaders and I have deleted the '.pipe(map((response) => response.json().response));'. The options search:params.toString() wasn't work on HttpParams and as recommended I have changed to params only.

But the requests are not working as they should :(

Before (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;
        }
    }

}



After (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;
        }
    }

}



I'm assuming that the variable this.http is of type HttpClient . The type definition for HttpClient.get() states that the options argument has an optional property params with the type:

params?: HttpParams | { [param: string]: string | string[]; };

It cannot be a single string (which is what params.toString() returns). It is either a key-value object of strings or an HttpParams object.

You can just pass your params variable directly, since it has the type HttpParams .

Instead of

{ headers: this.headers, params: params.toString() }

Just do

{ headers: this.headers, params }

But isn't params always empty in both cases? You initialize an empty object and don't add anything to it (unless you omitted that part).

Edit:

After seeing your full code I can explain what's going on with the params being empty.

On the URLSearchParams class, the set() method is a void method which mutates the object and returns nothing. In the original code what they are doing is creating an empty object, setting a bunch of values on it, and then converting it to a string. (I asked the question about it being empty because the parts with params.set() weren't part of your example code).

(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.

The HttpParams class works differently. Rather than updating itself with the value that you set, it returns a new instance.

(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.

But you aren't doing anything with the returned value since the original code was build expecting a void method. You need to be changing the value of params to the returned value each time that you set something. Change each const params to let params so that we can overwrite it. Then replace all calls to params.set() with params = params.set() . Like this:

let params: HttpParams = new HttpParams();
params = params.set('page', page.toString());
params = params.set('size', size.toString());
params = params.set('sort', sort);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM