【发布时间】:2017-04-04 21:09:21
【问题描述】:
我绑定了一个变量:
<span *ngIf="myVoltage && myVoltage>=0" > - {{myVoltage | number: '.0-0'}}</span>
ngIf
根据 {expression} 删除或重新创建 DOM 树的一部分。
'myVoltage' 为空,因为它是从服务器检索的,因此如果执行{{myVoltage | number: '.0-0'}},它会抛出某种空异常。这就是为什么我将它放在 span 中:
<span *ngIf="myVoltage && myVoltage>=0" >...</span>
但是它STILL在跨度内的对象上执行绑定和格式化,即使它不应该因为跨度不可见!
例外:null 不是对象(正在评估 'new Intl.NumberFormat(e,u)')
如果我删除| number: '.0-0',那么它会正常显示。然而,按原样,null 异常实际上会导致绑定中断,然后即使值不再为 null,它也永远不会显示。
我的设置信息:
Cordova CLI:6.2.0
离子框架版本:2.0.0-rc.1
Ionic CLI 版本:2.1.8
离子应用程序库版本:2.1.4
Ionic App 脚本版本:0.0.30
ios 部署版本:1.9.0
ios-sim 版本:5.0.11
操作系统:macOS Sierra
节点版本:v6.7.0
Xcode 版本:Xcode 8.1 Build 8B62 版
"dependencies": {
"@angular/common": "2.0.0",
"@angular/compiler": "2.0.0",
"@angular/compiler-cli": "0.6.2",
"@angular/core": "2.0.0",
"@angular/forms": "2.0.0",
"@angular/http": "2.0.0",
"@angular/platform-browser": "2.0.0",
"@angular/platform-browser-dynamic": "2.0.0",
"@angular/platform-server": "2.0.0",
"@ionic/storage": "1.0.3",
"ionic-angular": "2.0.0-rc.1",
"ionic-native": "2.0.3",
"ionicons": "3.0.0",
"moment": "2.14.1",
"ng2-translate": "3.0.0",
"rxjs": "5.0.0-beta.12",
"zone.js": "0.6.21"
},
"devDependencies": {
"@ionic/app-scripts": "0.0.30",
"i18next-conv": "3.0.3",
"typescript": "2.0.6"
},
我也试过了:
*ngIf="!!busVoltage && busVoltage>=0"
[ngIf]="busVoltage && busVoltage>=0"
编辑 1
所以根据Angular 2 documentation这是正确的做事方式:
<!-- because of the ngIf guard
nullHero.firstName never has a chance to fail -->
<div *ngIf="nullHero">Hello, {{nullHero.firstName}}</div>
编辑 2
所以根据source code:
/**
* 警告:此管道使用国际化 API。
* 因此它只在 Chrome 和 Opera 浏览器中可靠。对于其他浏览器,请使用
* polyfill,例如:[https://github.com/andyearnshaw/Intl.js/].
并且根据this answer我需要添加“intl”库,但是我使用了NPM,我不知道在哪里放置以下内容:
import 'intl';
import 'intl/locale-data/jsonp/en';
【问题讨论】: