Ways to extract information from a database using a parameter

I am currently working with angular cli version 8.1.0 and I have a requirement to pass parameters in the URL and retrieve data from a PHP MySQL database. On the PHP side, everything is functioning correctly and the URL looks like this: http://localhost/repos/Sportaz-repo/AdminStore/angular_admin/php/index.php?id=4

However, I am facing challenges in retrieving the data along with the parameter.

approval.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { ApiService } from 'src/app/api.service';

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

  constructor(private activatedRoute:ActivatedRoute,private apiService:ApiService) { }

  id:any;
  result:any;

  ngOnInit() 
  {
    this.id=this.activatedRoute.snapshot.paramMap.get('id');
    console.log(this.id);

    this.activatedRoute.queryParamMap.subscribe((queryParams:Params)=>{
      let vendorId=queryParams['id'];
      this.apiService.getVendorById(vendorId)
      .subscribe(data=>{
        this.result=data;
      });
    });
  }
}

api.service.ts

import { Injectable, Output,EventEmitter } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Users } from './users';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService { 
  constructor(private httpClient : HttpClient) { }\

  getVendorById(data)
  {
    let datas=JSON.stringify({'id':data});
    return this.httpClient.get('http://localhost/repos/Sportaz-repo/VaamozWeb/VaamozBusiness/RestApi/VaamozStore/AdminStore/angular_admin/php/index.php?id='+datas)
    .map(response => response.json() );
  }
}

index.php

<?php
    $conn=mysqli_connect("localhost","root","root","angdb");        
    $request=$_SERVER['REQUEST_METHOD'];

    $data=array();
    switch($request)
    {
        case 'GET':
            response(getData());
            break;

        default:
            #code...
            break;
    }

    function getData()
    {
        global $conn;

        if(@$_GET['id'])
        {
            @$id=$_GET['id'];

            $where="AND id=".$id;
        }
        else
        {
            $id=0;
            $where="";
        }


        $query=mysqli_query($conn,"select * from vendor where status='pending' ".$where);
        while($row=mysqli_fetch_assoc($query))
        {
            $data[]=array("id"=>$row['id'],"changeColumn"=>$row['changeColumn'],"type"=>$row['type'],"timestamp"=>$row['timestamp'],"status"=>$row['status'],"name"=>$row['name']);
        }
        return $data;
    }

    function response($data)
    {
        echo json_encode($data);
    }
?>

approval.component.html

{{result.name}}

Answer №1

You can simply make a direct API call using the provided URL instead of utilizing the map function.

  fetchVendorDetails(data)
  {
    return this.httpClient.get('http://localhost/repos/Sportaz-repo/VaamozWeb/VaamozBusiness/RestApi/VaamozStore/AdminStore/angular_admin/php/index.php?id='+data);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Introduce AngularJS version 2 for better web development

I'm facing an issue with using provide in Bootstrap, and here's my code snippet: import { NgModule, provide } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from &apo ...

Node.js server containerized with Docker: deleted express route remains accessible

I recently developed a Twitch Chat Bot using Dockerized (docker compose), Node.js v16 with express. To create an authorize-page for users to authorize my bot on the Twitch API, I utilized the route /auth/request: this.serverUrl = serverUrl; this.port = po ...

Issues with Testing Angular 7 Components with RouterTestingModule and Accessing getCurrentNavigation()

I am currently facing a challenge while testing a component that utilizes routerLink in the template (handled by RouterTestingModule) and getCurrentNavigation() in the corresponding ts file to access navigation state information. Initially, I attempted to ...

Can TypeScript support promise chaining in a functional way?

It appears that in the realm of JavaScript, one has the capability to execute: function extendPromise(promise) { return promise.then(new Promise(() => {})); } However, when incorporating types into the mix, such as function extendTypeScriptPromis ...

Using TypeScript for Routing in Angular

I encountered an error message that says the module 'route' is not available. I'm not sure why this is happening, any thoughts? "Uncaught Error: [$injector:nomod] Module 'route' is not available! You either misspelled the module n ...

Could JSON be the solution for combining a number and a string in a single key-value pair?

I am working on defining a nested JSON object that will store a key value pair with an integer (representing the amount of something) in use case 1, and a key value pair with a string (UUID) in use case 2. The ultimate goal is to analyze this data in futu ...

Challenges encountered when implementing a personal library in a separate project

After updating a library I own, I seem to have encountered an issue when trying to use it in another project. However, the reason for this problem eludes me. A multitude of error logs with a similar theme are appearing: ERROR in ./node_modules/@company-na ...

Best practices for utilizing forwardRef and next/dynamic in next.js version 13.4 with the "react-email-editor" component

I've been attempting to utilize the "react-email-editor" library in a Next.js project. My goal is to copy the email content generated within the editor to the clipboard. Since the library relies on browser interaction and the use of the "window" objec ...

Challenges with promises in Angular Firebase Realtime DB

Having some difficulties with Angular and Firebase Realtime DB. In my database service, I created a function like this: getAllProject() { return firebase.database().ref('project').once('value').then((snapshot) => { if (snapsh ...

Accessing the total number of items from a service in Angular

I am facing an issue with my cart-service and 2 components. The product-list component is responsible for displaying the products along with a buy button. However, the top-bar component seems to have trouble displaying the count when I try to directly call ...

There seems to be an issue with AppModule in your code. The error message states that it is not recognized as an NgModule and the problem

After upgrading to node 6, angular 4, typescript 2.3.2, and @angular/cli 1.02, I meticulously followed the steps outlined in the Guide for updating @angular/cli. I will include my entire package.json below in case there are any relevant details. The specif ...

How do rxjs Subjects and EventEmitters impact the performance of an Angular application?

I'm currently working on passing an event to a child component from the parent element. This is how my code structure looks: Parent Component HTML: ... <child-component [validate]="emitValidateAsObservable"> <child-component [validate]="em ...

Is it necessary to wait for the resolve function when using hooks in SvelteKit?

i have implemented this handle function for SvelteKit hooks and since it returns a promise of response, the resolve function does not necessarily need to be awaited. This is because it is a function that either directly returns a value or returns a promise ...

The 'any' type is automatically assigned to Angular and Element since the type 'IData' lacks an index signature

Looking to display specific object properties based on predefined keys in an array? Here's an example using TypeScript: const dataObject: IData = { a: 1, b: 2, c: 3 }; const dataKeys: string[] = ['a', 'c']; dataKeys.forEach((key: ...

Missing Directory Issue Upon Deploying Node.js App on Google App Engine

I have a Node.js web application built using TypeScript and Koa.js that I am looking to deploy on Google App Engine. The code has already been transpiled into JavaScript and is stored locally in the ./dist/src/ directory. Essentially, I only need to depl ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Angular 6: Inconsistent performance of [(ngModel)] functionality

In my Angular 6 project, I am utilizing Bootstrap Modals to implement a specific functionality. Upon clicking the modify button, a modal window should appear with pre-filled values. https://i.sstatic.net/PIg0L.jpg Although I am using template-driven form ...

Angular subscription and observable continuously fetch information

I'm encountering an issue with utilizing subscriptions and observables Here is my code This is my inventory.service.ts getInventoryList = (page: string, pageSize,size) => { const userLocation = this.authService.getUserLocation(); let que ...

Error: TypeScript React SFC encountering issues with children props typing

I am currently working with a stateless functional component that is defined as follows: import { SFC } from "react"; type ProfileTabContentProps = { selected: boolean; }; const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, child ...

Guide on incorporating Bootstrap 4 beta.2 into an Angular 4 project

After attempting to install Bootstrap 4 version beta.2 along with its dependencies (jquery and popper.js), I encountered a strange problem. A SyntaxError message kept appearing in the console, specifically stating "SyntaxError: export declarations may only ...