【问题标题】:How to calculate data of api service and to display in a card in angular component如何计算api服务的数据并以角度组件显示在卡片中
【发布时间】:2019-12-31 14:42:03
【问题描述】:

我想在有角项目的卡片中显示,例如行的计数。要从 mysql 获取数据,我正在使用服务。

这里是服务数据:

 private _postsURL = "http://localhost:3003/all";

  constructor(private http: Http) {
    }

   getcount(): Observable<ICustomer[]> {
   return this.http
      .get(this._postsURL)
      .map((response: Response) => {
          return <ICustomer[]>response.json();
      })
      .catch(this.handleError);
    }

组件.ts

        getcount(): void {
        this.apiSerivce.getcount()
        .subscribe(
          resultArray => this._count = [resultArray[0]],
          error => console.log("Error :: " + error)
         )
         }

       ngOnInit(): void {
       this.getcount();

component.html

           <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col-12" *ngFor="let post of _count">
                        <h2 class="m-b-0"><i class="mdi mdi-buffer text- 
               warning"></i></h2>
                        <h3 class="">{{post}}</h3>
                        <h6 class="card-subtitle">Total Earnings</h6> 
                   </div>
                    <div class="col-12">
                        <ngb-progressbar [showValue]="false" 
             type="warning" [value]="50"></ngb-progressbar>

我只想使用从 api 获取的值来填充卡片。

【问题讨论】:

  • 首先要问一个问题,你为什么用Http而不是HttpClient
  • 你应该包括一个当前收到的数据的例子,即当你控制台记录 resultArray 响应时有什么?

标签: mysql node.js angular


【解决方案1】:

API 响应是一个异步事件,并且 ngOnInit 方法执行在它从后端调用获得响应之前完成,因此,只有当 _count 变量绑定在其中获得值时,您才应该呈现卡片部分视图,您可以通过添加 ngIf 根卡 html 元素上的指令如下。

  <div class="card" *ngIf="_count?.length > 0">
            <div class="card-body">
                <div class="row">
                    <div class="col-12" *ngFor="let post of _count">
                        <h2 class="m-b-0"><i class="mdi mdi-buffer text- 
               warning"></i></h2>
                        <h3 class="">{{post}}</h3>
                        <h6 class="card-subtitle">Total Earnings</h6> 
                   </div>
                    <div class="col-12">
                        <ngb-progressbar [showValue]="false" 
             type="warning" [value]="50"></ngb-progressbar>

【讨论】:

  • 错误类型错误:无法读取未定义的属性“长度”!
  • localhost:3003/all 这个 api 调用只返回一个数字:例如 2,我想在卡片中显示这个结果
  • app.get("/all", (req, res) => { const connection = mysql.createConnection({ host: '', user: '', password: '' , 数据库: '', }) const queryString = "SELECT COUNT() as Totali FROM customer WHERE country='Austria'" connection.query(queryString, (err, rows, fields) => { }
  • @Alia 示例中有错字,刚刚更正。应该是*ngIf="_count?.length &gt; 0"
  • 0"> 在类卡中使用 ngIF 我看不到卡:(
猜你喜欢
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 2021-05-11
  • 2018-03-06
  • 2021-02-15
相关资源
最近更新 更多