首页 > 解决方案 > 如何使用参数从数据库中获取数据

问题描述

我正在使用角度 cli 8.1.0。我想将参数传递给 url 并从 php mysql 中获取数据。我的 php 端工作正常,如下所示:http://localhost/repos/Sportaz-repo/AdminStore/angular_admin/php/index.php?id=4

但是我怎样才能用参数检索数据。

批准.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() );
  }
}

索引.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);
    }
?>

批准.component.html

{{result.name}}

标签: angulartypescriptfrontend

解决方案


我认为您不需要使用地图功能。只需使用 URL 调用 api 即可满足您的需求。

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

推荐阅读