【问题标题】:How can I easily display an array of codes from MongoDB in Angular?如何在 Angular 中轻松显示来自 MongoDB 的代码数组?
【发布时间】:2022-01-12 22:45:41
【问题描述】:

我正在尝试构建一个简单的应用程序,允许用户将代码提交到数据库并简单地将这些代码显示给他们。我的数据库模型看起来像this,其中的文本是要显示的实际代码。出于某种原因,我无法让代码显示在网页上,它可能很小。目前,网页上没有任何显示,但 API 测试在soapUI 中有效

这是我获取代码的 API

router.get("/codes", async(req, res) => {
  try {
    Code.find({}, function(err, codes) {
      if (err) {
        console.log(err);
        res.status(501).send({
          message: `MongoDB Exception: ${err}`,
        });
      } else {
        console.log(codes);
        res.json(codes);
      }
    });
  } catch (e) {
    console.log(e);
    res.status(500).send({
      message: `Server Exception: ${e.message}`,
    });
  }
});

我的代码架构

let codeSchema = new Schema(
  {
    text: { type: String, unique: true, dropDups: true },
  },

  { collection: "codes" }
);

module.exports = mongoose.model("Code", codeSchema);

我的 home.ts 文件

export class HomeComponent implements OnInit {
  codes = new MatTableDataSource<Code>([]);
  constructor(private http: HttpClient) {}

  fetchCodes(): void {
    this.http
      .get('http://localhost:3000/api/codes')
      .subscribe((res: Code[]) => {
        this.codes.data = res;
      });
  }

  ngOnInit(): void {
    this.fetchCodes();
    console.log(this.codes);
  }
}

和我的 HTML

  <ng-container matColumnDef="code">
    <th mat-header-cell *matHeaderCellDef> Codes </th>
    <td mat-cell *matCellDef="let code"> {{codes}} </td>
  </ng-container>

【问题讨论】:

  • 这是您的完整 HTML 文件还是您只是跳过了 table 标记?

标签: javascript angular typescript rest mean-stack


【解决方案1】:

试试这个:

<td mat-cell *matCellDef="let code"> {{codes | json}} </td>

【讨论】:

    【解决方案2】:

    您的 ts 文件还应该像这样定义显示的列:

    displayedColumns: string[] = ['code'];     
    

    你的 HTML 文件应该是这样的:

     <table mat-table [dataSource]="codes" class="mat-elevation-z8">
             
         <ng-container matColumnDef="code">
             <th mat-header-cell *matHeaderCellDef>Code</th>
             <td mat-cell *matCellDef="let code"> {{code}} </td>
         </ng-container>
                
                
         <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
         <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
     </table>
    

    只有当你的 API 返回一个字符串数组时,上述方法才有效。

    const codes = ['code1', 'code2', 'code3'];
    

    【讨论】:

    • 谢谢!我现在有一些东西要显示,但它显示为 [object Object]
    • @johnf 你的代码对象结构是什么?
    • 我在 TS 文件中有这两行:codes = new MatTableDataSource([]);显示列:string[] = ['code'];以及代码模式中的文本字段,我想知道我是否还需要以某种方式访问​​数据库中的文本字段
    • @johnf 尝试检查与console.log(res) 通话的结果。你能提供其中一个包含的对象吗?
    • 是的!我从 console.log link 得到这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2020-10-16
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多