【问题标题】:*ngFor does not display array data nor any error*ngFor 不显示数组数据也没有任何错误
【发布时间】:2020-07-30 00:25:23
【问题描述】:

目前正在使用 mongoDB 的 $filter aggregation,它已经能够从我的查询中产生预期的输出。问题出在我的 HTML 中,而 *ngFor 没有显示我的数据,也没有在控制台中显示任何错误。

为了更好地理解,这是我从 console.log 生成的 JSON:

下面是我的查询代码:

//api.js

router.get('/agent-policies/:name', (req, res) => {

    db.collection('users').aggregate([
        // Get just the docs that contain an agent element where agent is === req.params.name
        {$match: {'paPolicies.policy.agent': req.params.name}},
        {$project: {
            policy: {$filter: {
                input: '$paPolicies.policy',
                as: 'police',
                cond: {$eq: ['$$police.agent', req.params.name]}
            }},
            _id: 0
        }}
    ]).toArray((err, results) => {
        if (err) throw err;
        res.send(results);
    })

})

最后,我的模板代码:

//component.html

<div *ngFor='let police of agentPolicies'>
      {{police.relationship}}
</div>

agentPolicies 在我的component.ts 中被设置为数组:

agentPolicies: any = [];

由于代码没有产生任何错误,我认为问题出在我的 HTML 中,并且我没有正确使用 *ngFor。为了从我的 JSON 中显示 relationship 的值,我需要进行哪些更改?

【问题讨论】:

    标签: node.js angular mongodb typescript express


    【解决方案1】:

    因为relationshippolicy 数组的属性,也是它的第一个对象。您必须按如下方式更改您的 HTML,

    <div *ngFor='let police of agentPolicies?.policy'>  
          {{police.relationship}}
    </div>
    

     <div *ngFor='let police of agentPolicies'>  
      
          <div *ngFor='let pcy of police?.policy '>  
    
              {{pcy.relationship}}
    
           </div>
    
     </div>
    

    【讨论】:

    • 嘿@micronyks。感谢你的回答。您的第二次编辑为我解决了这个问题。我会接受的。
    【解决方案2】:

    这是您的 API 返回的内容:

    const agentPolicies = [
      {
        policy: [
          {
            relationship: '...',
            // ...
          }
        ]
      }
    ];
    

    注意每个对象都有一个属性policy,它本身就是一个对象数组。

    选项 1:循环策略

    在这种情况下,您需要遍历 HTML 中的每个策略数组:

    <div *ngFor='let police of agentPolicies'>
      <div *ngFor='let policy of police.policy'>
          {{policy.relationship}}
      </div>
    </div>
    

    选项 2:在 API 中修改查询

    如果每个对象只有一个策略,那么您的数据如下所示:

    const agentPolicies = [
      {
        policy: {
          relationship: '...',
          // ...
        }
      }
    ];
    

    那么您需要在api.js 中更新您的查询,以从您的数组中返回来自$project 的单个策略。查看$replaceRoot,了解如何用同一数组中的单个对象替换policy 数组。

    【讨论】:

    • 虽然我已经接受了一个答案,但我仍然感谢一个彻底的解释!谢谢你。这是我第一次使用 $filter 聚合,所以我不确定。
    • 此外,我已经将它设计为每个对象将有多个策略,所以这很好。
    猜你喜欢
    • 2019-02-21
    • 2016-06-28
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多