我只需要一个简单的angular应用程序来调用外部API (get请求)并测量应用程序需要多长时间来获取数据。
我的代码看起来像这样:
measureData(): {
this.t0 = performance.now();
this.errors = '';
this.getHello().subscribe(
(result: string) =>
{
this.text = result
console.log("test")
return this.text
},
error => {
this.errors = error.message
console.log(error.message)
return this.errors
}
)
this.t1 = performance.now();
this.test = this.t1 - this.t0;
console.log("Action took " + this.test + " milliseconds.")
this.times.push(this.test);
}
在这种情况下,我遇到了异步的麻烦。所以我试了一下:
main(){
this.measureData().subscribe(
(result: String) => {
this.measurePerformance();
}
)
}
measureData(): Observable<any> {
this.t0 = performance.now();
this.errors = '';
this.getHello().subscribe(
(result: string) =>
{
this.text = result
console.log("test")
return this.text
},
error => {
this.errors = error.message
console.log(error.message)
return this.errors
}
)
return
}
measurePerformance() {
this.t1 = performance.now();
this.test = this.t1 - this.t0;
console.log("Action took " + this.test + " milliseconds.")
this.times.push(this.test);
}
在这种情况下,我得到这个错误:
ERROR TypeError: Cannot read property 'subscribe' of undefined
发布于 2019-06-12 20:11:36
您可以使用以下各项来测量所用时间:
var start = new Date().getTime();
// Your code
var end = new Date().getTime();
var elapsedTime = end -start;
console.log("Time", elapsedTime );
发布于 2019-06-13 15:02:10
对于我的解决方案,我使用了await delay(500)
。
const delay = ms => new Promise(res => setTimeout(res, ms));
我的完整代码:
async measureData() {
this.errors = '';
const delay = ms => new Promise(res => setTimeout(res, ms));
for (let i = 0; i < this.numberMeasurements; i++) {
this.t0 = performance.now();
this.getHello().subscribe(
(result: string) => {
this.text = result
this.t1 = performance.now();
this.test = this.t1 - this.t0;
console.log("Action took " + this.test + " milliseconds.")
this.times.push(this.test);
console.log(result)
},
error => {
this.errors = error.message
console.log(error.message)
}
)
await delay(500);
}
}
https://stackoverflow.com/questions/56561012
复制相似问题