首页 > 解决方案 > 尝试从 DB 检索信息失败(Angular8,php)

问题描述

更新!我可以在预览中看到检索到的数据,但在HTML页面上什么也没有

在此处输入图像描述

更新2!为阿夸在此处输入图像描述

我想从我的数据库中显示操作系统类别,在此处输入图像描述 但我收到了这个错误。我知道这是很多代码,但我被卡住了。我的数据库在 OpenServer 上,我写在 .htaccess 中。我也依赖我教授的代码,但仍然没有任何效果


Header set X-Content-Type-Options nosniff
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, referrer-policy, X-Requested-With, Content-Type, Origin,
Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type"
Header set Access-Control-Allow-Methods "GET, PUT, POST, PATCH, DELETE, OPTIONS"

类别.ts

export class Category{
  num_os: number;
  name_os: string;
  constructor(num_os: number, name_os: string) {
    this.num_os = num_os;
    this.name_os = name_os;
  }
}

tovar.service.ts

import {Category} from './category';
import { Injectable } from '@angular/core';
import {HttpService} from './http.service';

@Injectable()
export class TovarService{
 category: Category[];
 constructor(private httpService: HttpService) {
   this.category = [];
 }
 getCategory = (): Category[] => {
   this.httpService.getCategory()
     .subscribe((resp: Response) => {
       for (let index in resp){
         let cat1: Category = new Category(resp[index].num_os, resp[index].name_os);
         this.category.push(cat1);
       }
     });
   return this.category;
 }
}

浏览.component.html

<ul style="list-style-type: none; color: whitesmoke;">
          <li>OS</li>
       <li *ngFor="let item of Categories; let i = index ">
            <a>{{item.name_os}}</a>
          </li>
</ul>

类别.php

<?
include('connection.php');
$result3=mysqli_query($connection, "SELECT * from OS") or die("can't retrieve");
if(&result3){
  $rows = mysqli_num_rows($result3);
  $obj1 = array();
  for($i =0; $i <$rows; ++$i){
    $row = mysqli_fetch_row($result3);
    $obj1[$i]["NUM_OS"] = $row[0];
    $obj1[$i]["NAME_OS"] = $row[1];
      }
  echo json_encode($obj1);
  mysqli_free_result($result3);
}
mysqli_close($connection);
?>

浏览组件.ts

import { Component, OnInit } from '@angular/core';
import {Category} from '../shared/category';
import {TovarService} from '../shared/tovar.service';

@Component({
  selector: 'app-browse',
  templateUrl: './browse.component.html',
  styleUrls: ['./browse.component.css']
})
export class BrowseComponent implements OnInit {
NewCategory: Category[];
  constructor(private tovarservice: TovarService) {
    this.NewCategory = [];
  }

  ngOnInit(): void {
    this.NewCategory = this.tovarservice.getCategory();
  }

}

http.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {HttpResponse, HttpHeaders} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import { map } from 'rxjs/operators';
import { catchError } from 'rxjs/operators';
import {Category} from './category';
import {enableProdMode} from '@angular/core';

@Injectable()
export class HttpService{
  constructor(private http: HttpClient) {}
  getCategory(){
    return this.http.get('http://localhost/category.php').pipe(
      map(resp => resp),
      catchError((error: any) => throwError(error)));
  }
}

标签: phpangulartypescript

解决方案


首先,请确保当您直接调用(curl 或在浏览器中)http://localhost/category.php时,它会返回所需的结果(在 json 中)。

之后在 src 文件夹的根目录中创建一个新文件proxy.conf.json :

{
    "/category.php": {
        "target": "http://localhost/category.php",
        "secure": false
    }
}

现在我们需要使用指向src/proxy.conf.json的架构师>服务>选项下的proxyConfig键配置angular.json,如下所示:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "demo:build"
  },
  "configurations": {
    "production": {
      "browserTarget": "demo:build:production",
      "proxyConfig": "src/proxy.conf.json" //this is the line to add
    }
  }
}

最后,像往常一样运行你的应用程序:ng serve

注意:不再需要 CORS 后端标头


推荐阅读