Home > database >  How put query params in Obsrvable call whit these service?
How put query params in Obsrvable call whit these service?

Time:05-26

How do I get to put this query params

users?page=2

in this Observable method?
I try to put queryParams: 'abd here' a param but i can't put a data that not be called yet

    getUsers(): Observable < Users > {
      this.spinner.show();
      const options: Options = {
        type: 'get',
        path: '/users',
        queryParams: '', // here is the ?page=2


      };
      return this.apiCall.call(options).pipe(
        tap((res) => {

          console.log('El servicio de usuarios funciona', res);
        }),
        finalize(() => {
          this.spinner.hide();
        }),
        catchError((er) => this.apiCall.handleError(er))
      );
    }

I get the page data from the same call These

but I need do it whit these 'apiCall' service

@Injectable({
  providedIn: 'root',
})
export class ApiCallService {
  protected basePath = 'https://localhost';
  public configuration = new Configuration();
  public defaultHeaders = new HttpHeaders();
  public encoder: HttpParameterCodec;

  constructor(protected httpClient: HttpClient, @Optional() configuration: Configuration) {
    if (configuration) {
      this.configuration = configuration;
    }

    if (typeof this.configuration.basePath !== 'string') {
      if (typeof this.basePath !== 'string') {
        this.basePath = this.basePath;
      }
      this.configuration.basePath = this.basePath;
    }
    this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
  }

  public createCall(options: Options): Observable<any> {
    // Create Default Header
    let headers = this.defaultHeaders;

    // Check url config
    this.configuration.basePath = this.configuration.basePath ? this.configuration.basePath : this.basePath;

    // Add headers
    const queryHeaders: any = {};

    if (options.hasOwnProperty('headers')) {
      Object.assign(queryHeaders, options.headers);
    }

    for (const h in queryHeaders) {
      if (queryHeaders.hasOwnProperty(h)) {
        headers = headers.set(h, queryHeaders[h]);
      }
    }

    // authentication (bearer) required
    if (this.configuration.accessToken || options.accessToken) {
      const accessToken = this.configuration.accessToken || options.accessToken;
      headers = headers.set('Authorization', 'Bearer '   accessToken);
    }
    let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;

    if (httpHeaderAcceptSelected === undefined) {
      // to determine the Accept header
      const httpHeaderAccepts: string[] = ['application/json'];
      httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
    }

    if (httpHeaderAcceptSelected !== undefined) {
      headers = headers.set('Accept', httpHeaderAcceptSelected);
    }

    // Choose http Call
    let params = '';

    if (options.params) {
      options.params.forEach((param) => {
        params = params   `/${encodeURIComponent(String(param))}`;
      });
    }
    const url = `${this.configuration.basePath}${options.path}`;

    const typesCall = {
      get: this.httpClient.get(`${url}${params}`, {
        params: options.queryParams,
        headers,
      }),
      put: this.httpClient.put(url, options.body, {
        params: options.queryParams,
        headers,
      }),
      post: this.httpClient.post(url, options.body, {
        params: options.queryParams,
        headers,
      }),
      patch: this.httpClient.patch(url, options.body, {
        params: options.queryParams,
        headers,
      }),
      delete: this.httpClient.delete(`${url}${params}`, {
        params: options.queryParams,
        headers,
      }),
    };
    return typesCall[options.type];
  }

  call(options: Options): Observable<any> {
    return this.createCall(options).pipe(
      map((res) => res),
      catchError(this.handleError)
    );
  }

  public handleError(error: Response): Observable<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return throwError(() => error || 'server error');
  }
}

I need do it whit these service i think i can get param call in these service but i dont rememeber how
thanks for all i'm stuck on this

CodePudding user response:

To get paginated results transformed into an array of users you can do this:

export type User = {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  avatar: string;
};

export type UserPage = {
  page: number;
  per_page: number;
  total: number
  total_pages: number;
  data: User[];
};

  getUserPage(startPage): Observable <UserPage> {
    const params: HttpParams = new HttpParams();
    params.append("page", startPage);

    const options: Options = {
      type: 'get',
      path: '/users',
      queryParams: params,
    };
    return this.apiCall.call(options).pipe(
      tap((res) => {
        console.log('El servicio de usuarios funciona', res);
      }),
      catchError((er) => this.apiCall.handleError(er))
    );
  }


  getUsers(): Observable<User[]> {
    this.spinner.show();
    return this.fetchPage(1).pipe(
      expand(({ page, total_pages }) =>
        page < total_pages ? this.fetchPage(page 1) : EMPTY
      ),
      concatMap(({ data }) => data),
      toArray(),
      finalize(() => {
        this.spinner.hide();
      }),
    );
  }

This is based on RxJs Observable Pagination

  • Related