【问题标题】:Cant access array element inside html table无法访问html表中的数组元素
【发布时间】:2019-04-20 14:30:54
【问题描述】:

你好,我正在做关于酒吧啤酒饮用者的数据库项目。我正在对我的数据库运行查询并使用 Angular 将其显示在本地主机网站上。我可以看到查询执行并获得结果。对于给定的饮酒者,我运行一个查询,获取他们在各个酒吧进行的所有交易,所以我试图显示的只是给定人的交易。我正确地创建了所有内容,因为当我使用邮递员时可以看到它,甚至可以在本地主机上检查元素下的网络选项卡中的请求中看到它。我什至可以在页面上打印出一个元素,但是一旦我尝试在我的 HTML 中的表格内打印它就不起作用,我不知道为什么,我尝试了查找时的感觉,但它没有似乎可以工作,我会非常感谢您的帮助。

这是我正在运行的服务器下的 database.py 中的代码

def get_drinker_trans(name):
    with engine.connect() as con:
            query = sql.text(
                    "select b1.id, b1.bar, t1.item, b1.time, b1.date, t1.count, s1.price from Bills b1, Transactions t1, Sells s1 where b1.drinker = :name and t1.item in (select item from Beers) and b1.id = t1.bill and s1.bar = b1.bar and s1.item = t1.item order by b1.date"
            )
            rs = con.execute(query, name = name)
            results = [dict(row) for row in rs]
            for r in results:
                    r['price'] = float(r['price'])
            for r in results:
                    r['count'] = int(r['count'])
            return results

这是我服务器中 init.py 中的应用路由

@app.route("/api/drinkers/<name>", methods=["GET"]) def get_drinker_trans(name): try: if name is None: raise ValueError("Drinker not not found") return jsonify(database.get_drinker_trans(name)) except ValueError as e: return make_response(str(e), 400) except Exception as e: return make_response(str(e), 500)

我的应用路由模块

  import { NgModule } from '@angular/core';
  import { Routes, RouterModule } from '@angular/router';
  import { WelcomeComponent } from './welcome/welcome.component';
  import { BarDetailsComponent } from './bar-details/bar-details.component';
  import { BeersComponent } from './beers/beers.component';
  import { DrinkersComponent } from './drinkers/drinkers.component';
  import { DrinkerDetailsComponent } from './drinker-details/drinker-details.component';

  const routes: Routes = [

{
  path: '',
  pathMatch: 'full',
  redirectTo: 'bars'
},
{
  path: 'bars',
  pathMatch: 'full',
  component: WelcomeComponent
},
{
  path: 'bars/:bar',
  pathMatch: 'full',
  component: BarDetailsComponent
},
{
  path: 'beers',
  pathMatch: 'full',
  component: BeersComponent
},
{
  path: 'drinkers',
  pathMatch: 'full',
  component: DrinkersComponent
},
{
  path: 'drinkers/:drinker',
  pathMatch: 'full',
  component: DrinkerDetailsComponent
}];

  @NgModule({
   imports: [RouterModule.forRoot(routes)],
exports: [RouterModule] }) export class AppRoutingModule { }

我的饮酒者服务文件,我在其中说明交易是什么以及由哪些组成

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

  export interface Transaction{
bar: string;
count: number;
date: string;
id: string;
item: string;
price: number;
time: string; }

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

constructor(private http: HttpClient) { }

getDrinkers(){
  return this.http.get<any[]>('/api/drinker')
}

//getDrinker(drinker:string){
//  return this.http.get<any[]>('/api/drinker/' + drinker)
//}

get_Trans(drinker:string){
  return this.http.get<Transaction[]>('/api/drinkers/' + drinker);
} }

我的饮酒者详细信息组件

  import { Component, OnInit } from '@angular/core';
  import { DrinkersService, Transaction } from '../drinkers.service';
  import { ActivatedRoute } from '@angular/router';
  import { HttpResponse } from '@angular/common/http';

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

drinkerName : string;
//drinkerDetails : any[];
trans: Transaction[];

constructor(
  public drinkerService: DrinkersService,
  public route: ActivatedRoute,
) {
  this.route.paramMap.subscribe((paramMap) => {
  this.drinkerName = paramMap.get('drinker');

  /*drinkerService.getDrinker(this.drinkerName).subscribe(
  data =>{
    //this.drinkerDetails = data;
  },
  (error: HttpResponse<any>) => {
    if (error.status === 404){
      alert('Dinker not found');
    }
    else{
      console.error(error.status + '-' + error.body);
      alert('error occurred on the server. please check the browser console');
    }
  }
  );*/


  this.drinkerService.get_Trans(this.drinkerName).subscribe(
    data => {
      this.trans = data;
    },
    (error: HttpResponse<any>) => {
      if (error.status === 404){
        alert('Drinker not found');
      }
      else{
        console.error(error.status + '-' + error.body);
        alert('error occurred on the server. please check the browser console');
      }
    }
  );



}); }

ngOnInit() {
}

}

我的 html 代码可以访问表外但不能访问的数组,我尝试了循环和其他方法,但它不起作用

<div class="jumbotron jumbotron-fluid">
<div class="container">
  <h1 class="display-4"></h1>
  <p class="drinker-details"></p>
</div>

<br>
{{trans[0].bar}}
<br>


<div class="container">
   <h2 class="text-center font-weight-light">Transactions</h2>
<br>
<p-table [value]="Transactions">
  <ng-template pTemplate="header">
    <tr>
      <th>Bar</th>
      <th>Count</th>
      <th>Date</th>
      <th>ID</th>
      <th>Item</th>
      <th>Price</th>
      <th>Time</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-trans>
    <tr>
      <td>{{trans.bar}}</td>
      <td>{{trans.count}}</td>
      <td>{{trans.date}}</td>
      <td>{{trans.id}}</td>
      <td>{{trans.item}}</td>
      <td>{{trans.price}}</td>
      <td>{{trans.time}}</td>
    </tr>
  </ng-template>
</p-table>

运行时的样子

Shows that that one element being displayed but can display in table

when i right click and do inspect element and go to network table and have the GET on the person Aaron Rodgers and the return results of the query

【问题讨论】:

    标签: html angular html-table


    【解决方案1】:

    在您的组件中,您的数据未正确分配。

    this.drinkerService.get_Trans(this.drinkerName).subscribe(
        data => {
          this.trans = JSON.parse(data);
        },
        (error: HttpResponse<any>) => {
          if (error.status === 404){
            alert('Drinker not found');
          }
          else{
            console.error(error.status + '-' + error.body);
            alert('error occurred on the server. please check the browser console');
          }
        }
      );
    

    【讨论】:

      【解决方案2】:

      尝试换行

      <p-table [value]="Transactions">
      

      <p-table [value]="trans">
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-08
        • 1970-01-01
        • 1970-01-01
        • 2021-04-23
        • 2020-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多