我在Angular2服务中有一个函数,它通过Promise.resolve返回Mock数据,当用.then解包时,它给了我一个空的promise对象.我可以看到调用函数在传递到__zone_symbole__value属性之前接收带有有效负载的Promise.然后在内部.然后我似乎只剩下一个空承诺.
getTemperatureData(): Promise<any> { let data = this.convertJSONToGoogleChartTable(temperatureData_JSON); let p = Promise.resolve(data); return p; }
使用Chrome我看到上面的p看起来像
ZoneAwarePromise {__ zone_symbol__state:true,__ zone_symbol__value:“[[”Date“,”Temperature“,”LowTemperature“],[”05/11/2 ……“,69.02,null],[”2016/11/11 23:54: 34\”,69.99,空]]“}
getTemperatureData() { var d = this.dataService.getTemperatureData(); d.then(data => this.line_ChartData = data); }
当我看到d时,我看到与上面的p相同
ZoneAwarePromise {__ zone_symbol__state:true,空]]“}
问题发生在.then,其中“d”的值只是一个空的承诺.以下内容取自Chrome开发工具控制台,以显示我所看到的内容.
d.then(data => console.log(data)) ZoneAwarePromise {__zone_symbol__state: null,__zone_symbol__value: Array[0]}
无论我做什么以及我尝试了多少组合,我都无法获得d中的数据. (注意,p和d只是临时破坏代码的.)
我的package.json如下:
{ "name": "angular2","version": "0.0.0","license": "MIT","angular-cli": {},"scripts": { "start": "ng serve","lint": "tslint \"src/**/*.ts\"","test": "ng test","pree2e": "webdriver-manager update","e2e": "protractor" },"private": true,"dependencies": { "@angular/common": "~2.1.0","@angular/compiler": "~2.1.0","@angular/core": "~2.1.0","@angular/forms": "~2.1.0","@angular/http": "~2.1.0","@angular/material": "^2.0.0-alpha.9-3","@angular/platform-browser": "~2.1.0","@angular/platform-browser-dynamic": "~2.1.0","@angular/router": "~3.1.0","core-js": "^2.4.1","ng2-bootstrap": "^1.1.16","node-MysqL": "^0.4.2","rxjs": "5.0.0-beta.12","ts-helpers": "^1.1.1","zone.js": "^0.6.23" },"devDependencies": { "@types/jasmine": "^2.2.30","@types/node": "^6.0.42","angular-cli": "1.0.0-beta.19-3","codelyzer": "1.0.0-beta.1","jasmine-core": "2.4.1","jasmine-spec-reporter": "2.5.0","karma": "1.2.0","karma-chrome-launcher": "^2.0.0","karma-cli": "^1.0.1","karma-jasmine": "^1.0.2","karma-remap-istanbul": "^0.2.1","protractor": "4.0.9","ts-node": "1.2.1","tslint": "3.13.0","typescript": "~2.0.3","webdriver-manager": "10.2.5" } }
the value of data is just an empty promise
这告诉我convertJSONToGoogleChartTable正在返回一个承诺,而你并没有链接你对它的承诺.
请注意,如果您使用的是比任何类型更强的类型,TypeScript编译器可能会为您捕获此类型.
由于您在获取该数据后没有做任何事情,您可以这样做:
getTemperatureData(): Promise<any> { return this.convertJSONToGoogleChartTable(temperatureData_JSON); }
但是如果你想在返回之前对这些数据做些什么,你可以在原来的承诺中锁定它:
getTemperatureData(): Promise<any> { return this.convertJSONToGoogleChartTable(temperatureData_JSON) .then(data => { console.log(data); return data; }); }