呈现 Angular 组件时出现一般错误
Generic error when rendering an Angular component
我有一个简单的组件,但由于某种原因我收到以下运行时错误:
An unhandled exception occurred while processing the request.
Exception: Call to Node module failed with error: Error: Uncaught (in promise): TypeError: Cannot read property 'Name' of undefined
TypeError: Cannot read property 'Name' of undefined
at CompiledTemplate.proxyViewClass.View_ProductDetailsComponent0.detectChangesInternal (/AppModule/ProductDetailsComponent/component.ngfactory.js:106:69)
下面是视图:
<h2>{{product.Name}}</h2>
<strong>Price: {{product.Price | currency}}</strong>
<div style="background-color:aliceblue;border:hidden;border-radius:15px;">
<h4>Add to Cart</h4>
<form name="myForm">
Quantity: <input type="number" [(ngModel)]="quantity" placeholder="quantity" name="quantity"/>
<input type="button" (click)="AddToCart()" ng-disabled="myForm.$invalid" value="Add" class="btn btn-default" />
</form>
</div>
如果组件内的 product
字段是 undefined
,这很可能会发生。为了防止这种情况,您可以使用安全导航运算符(它基本上会进行真实检查):
{{product?.Name}}
或在模板中进行 if 检查:
<div *ngIf="product">
{{product.Name}}
</div>
我有一个简单的组件,但由于某种原因我收到以下运行时错误:
An unhandled exception occurred while processing the request.
Exception: Call to Node module failed with error: Error: Uncaught (in promise): TypeError: Cannot read property 'Name' of undefined TypeError: Cannot read property 'Name' of undefined at CompiledTemplate.proxyViewClass.View_ProductDetailsComponent0.detectChangesInternal (/AppModule/ProductDetailsComponent/component.ngfactory.js:106:69)
下面是视图:
<h2>{{product.Name}}</h2>
<strong>Price: {{product.Price | currency}}</strong>
<div style="background-color:aliceblue;border:hidden;border-radius:15px;">
<h4>Add to Cart</h4>
<form name="myForm">
Quantity: <input type="number" [(ngModel)]="quantity" placeholder="quantity" name="quantity"/>
<input type="button" (click)="AddToCart()" ng-disabled="myForm.$invalid" value="Add" class="btn btn-default" />
</form>
</div>
如果组件内的 product
字段是 undefined
,这很可能会发生。为了防止这种情况,您可以使用安全导航运算符(它基本上会进行真实检查):
{{product?.Name}}
或在模板中进行 if 检查:
<div *ngIf="product">
{{product.Name}}
</div>