# How to make API call?

WARNING

Vuexy Angular use fakeBackendProvider to create fake backend API call, comment it in app.module.ts file while using real api.

// ! IMPORTANT: fakeBackendProvider used to create fake backend API call, comment while using real api
// fakeBackendProvider

Refer the below sample code to make real API call, we have tested this in faq.service.ts For your project you can create service file sample.service.ts.

User router resolver to make an API call and get the data which requires on page load. You can also create API method i.e getUserbyID to call it when it needed.

import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'

import { BehaviorSubject, Observable } from 'rxjs'

@Injectable()
export class FAQService implements Resolve<any> {
  rows: any
  onFaqsChanged: BehaviorSubject<any>
  configUrl = 'https://reqres.in/api/users'
  users: any
  /**
   * Constructor
   *
   * @param {HttpClient} _httpClient
   */
  constructor(private _httpClient: HttpClient) {
    // Set the defaults
    this.onFaqsChanged = new BehaviorSubject({})
  }

  /**
   * Resolver
   *
   * @param {ActivatedRouteSnapshot} route
   * @param {RouterStateSnapshot} state
   * @returns {Observable<any> | Promise<any> | any}
   */
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
    return new Promise<void>((resolve, reject) => {
      console.log('RESOLVER')
      Promise.all([this.getDataTableRows(), this.getUsersList()]).then(users => {
        this.users = users
        resolve()
      }, reject)
    })
  }

  /**
   * Get UsersList: API Call made on page load
   */
  getUsersList(): Promise<any[]> {
    return new Promise((resolve, reject) => {
      this._httpClient.get('https://reqres.in/api/users').subscribe((response: any) => {
        console.log(response)
        resolve(response)
      }, reject)
    })
  }

  /**
   * Get getUser by ID: API Call made manually onInit
   */
  getUserbyID(id) {
    return this._httpClient.get('https://reqres.in/api/users/' + id)
  }

  /**
   * Get rows: API Call made on page load
   */
  getDataTableRows(): Promise<any[]> {
    return new Promise((resolve, reject) => {
      this._httpClient.get('api/faq-data').subscribe((response: any) => {
        this.rows = response
        this.onFaqsChanged.next(this.rows)
        resolve(this.rows)
      }, reject)
    })
  }
}

Now, our service is ready. Let's make an api call from our component TS file.

import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'

import { Subject } from 'rxjs'
import { takeUntil } from 'rxjs/operators'

import { FAQService } from 'app/main/pages/faq/faq.service'

@Component({
  selector: 'app-faq',
  templateUrl: './faq.component.html',
  styleUrls: ['./faq.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FaqComponent implements OnInit, OnDestroy {
  // public
  public contentHeader: object
  public data: any
  public searchText: string

  // private
  private _unsubscribeAll: Subject<any>

  /**
   * Constructor
   *
   * @param {FAQService} _faqService
   */
  constructor(private _faqService: FAQService) {
    this._unsubscribeAll = new Subject()
  }

  // Lifecycle Hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On Changes
   */
  ngOnInit(): void {
    this._faqService.onFaqsChanged.pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      this.data = response
    })

    // API Call made manually onInit
    this.getUser()
  }

  /**
   * Get getUser
   */
  getUser() {
    this._faqService.getUserbyID(2).subscribe(
      data => {
        console.log(data)
      },
      err => console.error(err),
      () => console.log('done loading foods')
    )
  }

  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next()
    this._unsubscribeAll.complete()
  }
}
Last Updated: 7/7/2021, 3:41:52 PM