Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a generic request service in Angular8

i've created an generic request service but it keeps returning 'ZoneAwarePromise'. I've tried to use .pipe() and .subscribe() to try to retrive the content of the request, but it's not working.

requester.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RequesterService {

  constructor(private http: HttpClient) { }

  request(method, url, headers, body, params) {
    return this.http.request(method, url, {
      body: body || {},
      headers: headers || {},
      params: params || {}
    })
  }

  async get(url, params?, headers?, data?) {
    return await this.request('get', url, params, headers, data)
  }

  async post(url, params, headers, data) {
    return await this.request('post', url, params, headers, data);
  }

  async put(url, params, headers, data) {
    return await this.request('put', url, params, headers, data);
  }

  async delete(url, params, headers, data) {
    return await this.request('delete', url, params, headers, data);
  }
}

gym-list.component.ts

import { Component, OnInit } from '@angular/core';
import { RequesterService } from 'src/app/core/Requester/requester.service';

@Component({
  selector: 'app-gym-list',
  templateUrl: './gym-list.component.html',
  styleUrls: ['./gym-list.component.css']
})
export class GymListComponent implements OnInit {

  constructor(private Requester: RequesterService) { }

  ngOnInit() {
    console.log(this.teste())
  }

  async teste() {
    await this.Requester.get('https://searchs.glitch.me/proposalcontent')
  }
}
like image 679
Felipe Santos Avatar asked Sep 10 '25 22:09

Felipe Santos


2 Answers

import { HttpClient, HttpHeaders, HttpRequest, HttpEventType, HttpEvent, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { Observable, from } from 'rxjs';
import { IGenericHttpClient } from './igeneric-http-client';
import { Injectable } from '@angular/core';
import { HttpMethod } from '../view-models/component-type.enum'
import { IRequestOptions } from '../view-models/interface';
import { EnvironmentViewModel } from '../view-models/environment-view-model';
import { retry } from 'rxjs/operators';
@Injectable()
export class GenericHttpClient<T> implements IGenericHttpClient<T>{

  constructor(private httpClient: HttpClient, private environment: EnvironmentViewModel) { }

  public Post(destinationUrl: string, options?: IRequestOptions): Observable<T> {
    return this.request<T>(HttpMethod.Post, destinationUrl, options);
  }

  public Put(destinationUrl: string, options?: IRequestOptions): Observable<T> {
    return this.request<T>(HttpMethod.Put, destinationUrl, options);
  }

  public Get(destinationUrl: string, options?: IRequestOptions): Observable<T> {
    return this.request<T>(HttpMethod.Get, destinationUrl, options);
  }

  public Delete(destinationUrl: string, options?: IRequestOptions): Observable<T> {
    return this.request<T>(HttpMethod.Delete, destinationUrl, options);
  }

  private request<T>(method: string, url: string, options?: IRequestOptions): Observable<T> {
    return Observable.create((observer: any) => {
      this.httpClient.request<T>(new HttpRequest(method, this.environment.baseUrl + url, options)).subscribe(
        (response: any) => {
          const responsTye = response as HttpEvent<any>
          switch (responsTye.type) {
            case HttpEventType.Sent:
              console.log('Request sent!');
              break;
            case HttpEventType.ResponseHeader:
              console.log('Response header received!');
              break;
            case HttpEventType.DownloadProgress:
              const kbLoaded = Math.round(responsTye.loaded / 1024);
              console.log(`Download in progress! ${kbLoaded}Kb loaded`);
              break;
            case HttpEventType.Response:
              observer.next(response.body);
              console.log('😺 Done!', responsTye.body);
          }
        },
        (error) => {
          switch (error.status) {
            case 403:
              observer.complete();
              break;
            default:
              observer.error(error);
              break;
          }
        }
      );
    });
  }
}
like image 156
San Jaisy Avatar answered Sep 13 '25 11:09

San Jaisy


You are trying to return an non-async function with await.

  request(method, url, headers, body, params) {
    return this.http.request(method, url, {
      body: body || {},
      headers: headers || {},
      params: params || {}
    })
  }

  async get(url, params?, headers?, data?) {
    return await this.request('get', url, params, headers, data)
  }

You shouldn't use async-await system here.

Try this:

  get(url, params?, headers?, data?) {
    return this.request('get', url, params, headers, data)
  }

And subscribe this method in your component.ts file.

Like this:

Requester.get.subscribe(....)
like image 37
canmustu Avatar answered Sep 13 '25 11:09

canmustu