我正在尝试建立一个使用Aurelia,Javascript和ES6的网站。
我有一个简单的类(状态),需要在一定间隔内从服务器获取一些数据。
更新资料
我已经按Fabio Luz的建议将CalcData添加到进样器中,但是仍然出现相同的错误。顺便说一句;)。
该类如下所示:
import {inject} from "aurelia-framework"; // for the inject decorator
import { StatusData } from "./statusData"; // MovieData, the module that will be injected
import { CalcData } from "./Calc"
@inject(StatusData, CalcData) // Inject decorator injects MovieData
export class Status {
constructor(StatusData, CalcData) {
this.statusData2 = StatusData;
this.CalcData = CalcData;
}
activate() {
setInterval(this.updateCalc, 3000);
}
updateCalc() {
this.CalcData.hello()
.then(statusData => this.statusData2 = statusData);
}
updateStatus() {
return statusData2.getX()
.then(statusData => this.statusData2 = statusData);
}
update() {
return 1;
}
}
updateCalc
函数被调用,但是当发生这种情况时,浏览器会说CalcData未定义。Uncaught TypeError: Cannot read property 'hello' of undefined
at updateCalc (status.js:17)
updateCalc @ status.js:17
status.js:17 Uncaught TypeError: Cannot read property 'hello' of undefined
at updateCalc (status.js:17)
updateCalc @ status.js:17
CalcData类如下所示:
import { inject } from "aurelia-framework"; // for the inject decorator
import { HttpClient } from "aurelia-http-client"; // for the http client that will be injected
let baseUrl = "/movies.json";
@inject(HttpClient)
export class CalcData {
constructor(httpClient) {
this.http = httpClient;
}
hello() {
return this.http.get(baseUrl)
.then(response => {
return response.content;
});
}
}
我似乎找不到问题,我环顾四周,但找不到解决方案。我必须说我是Aurelia的新手。
任何帮助深表感谢!
最佳答案
您的问题很可能是大写。
让我们看一下代码的开头:
import {inject} from "aurelia-framework"; // for the inject decorator
import { StatusData } from "./statusData"; // MovieData, the module that will be injected
import { CalcData } from "./Calc"
@inject(StatusData, CalcData) // Inject decorator injects MovieData
export class Status {
constructor(StatusData, CalcData) {
this.statusData2 = StatusData;
this.CalcData = CalcData;
}
请注意,构造函数正在使用其名称与您要注入的类的名称完全匹配的参数。这会导致运行时混乱,因为您可能最终将
this.Calcdata
设置为类CalcData
(与StatusData
相同)。该类没有名为hello()
的函数,只有该类的实例才具有该函数。如果将参数名称更改为不完全匹配,则问题将消失。@inject(StatusData, CalcData) // Inject decorator injects MovieData
export class Status {
constructor(statusData, calcData) {
this.statusData = statusData;
this.calcData = calcData;
}
我还将属性名称小写以匹配JavaScript命名约定。