gpt4 book ai didi

node.js - Angular 生产错误 : Property does not exist on type 'object'

转载 作者:可可西里 更新时间:2023-11-01 17:17:26 24 4
gpt4 key购买 nike

我有一个 Angular 7 应用程序从两个独立的端点检索数据:

  1. http://localhost:1337/sms
  2. http://localhost:1337/total

我可以成功地向开发中的这些端点发出 GET 请求。但是,当我运行 ng build --prod 时出现以下错误:

src/app/app.component.html(20,29) 中的错误::属性“total”在类型“object”上不存在。

作为测试,我暂时从 app.component.html 中删除了 {{ total.total }},再次运行 ng build --prod 并且成功了。

这不是向两个单独的端点发出 GET 请求的正确方法,还是我做错了其他事情,可能是在我的 Node 服务器文件中?

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
signees: object;
total: object;

constructor(private http: HttpClient){}

ngOnInit(): void {
this.http.get('http://localhost:1337/sms').subscribe(
data => {
this.signees = data;
}
);

this.http.get('http://localhost:1337/total').subscribe(
data => {
this.total = data;
}
);

}
}

相关app.component.html代码

<section class="page-section mx-auto">
<h3 class="text-center">{{ total.total }} people have signed the petition</h3>
<div class="container">
<div class="row">

<div class="col-sm-6 col-lg-3"
*ngFor="let signee of signees; index as i">
<div class="card">
<div class="card-body">
<p class="h2">{{ signee.name }}</p>
<ul class="signee-meta text-muted">
<li>#{{ i + 1 }}</li>
<li>{{ signee.date }}</li>
</ul>
</div>
</div>
</div>

</div><!-- row -->
</div><!-- container -->

</section>

/total 端点 (MongoDB)

app.get('/total', (req, res) => {
collection.countDocuments({}, function(err, num) {
assert.equal(null, err);
res.send({total: num});
});
});

编辑(添加数据结构)

数据结构(MongoDB)

{ 
"_id" : ObjectId("5c61e0b658261f10280b5b17"),
"name" : "Bill Kickok",
"number" : "+14950395584",
"date" : "2/11/19"
}

最佳答案

运行 ng build --prod 时会抛出此错误因为在幕后这种构建过程与提前编译一起工作。

这是基于 angular documentation 的 AOT 上发生的事情.

Detect template errors earlier

The AOT compiler detects and reports template binding errors during the build step before users can see them.

您收到该错误是因为您在声明 total 时尝试呈现 total 对象的属性作为object .

为了摆脱这个错误,你应该创建一个 interface对于这个变量。例如

export interface Total {
total: number
// any other properties total might include
}

然后像这样在您的组件中使用此接口(interface)进行类型定义:

total: Total

如果您不想创建接口(interface) - 这是一种不好的做法 - 您可以将总数定义为 any (total: any)。

最后直接制作http在您的组件中请求也是一种不良做法。您应该创建一个服务,然后添加那些 methods负责与您的后端通信,然后将该服务注入(inject)您的组件并调用该方法。

我建议您进一步查看 angular documentation .

关于node.js - Angular 生产错误 : Property does not exist on type 'object' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54755236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com