我使用以下代码。
export class AppComponent {
id:string;
url:string = "https://jsonplaceholder.typicode.com/posts/";
title:string;
found:boolean;
constructor(private httpClient:HttpClient) {}
//https://jsonplaceholder.typicode.com/posts
onNameKeyUp(event:any) {
this.id = event.target.value;
this.found = false;
}
getProfile() {
console.log("getProfile gestartet");
var newurl = this.url.concat(this.id);
//var newurl = this.url;
this.httpClient.get(newurl)
.subscribe(
(data:any[]) => {
console.log(data);
console.log(data.length);
if(data.length) {
this.title = data[0].title;
this.found = true;
} else {
console.log("No data.length exist: " + newurl);
}
}
);
}
}
控制台中的输出是:
我每次都得到一个数据数组,但我不能得到这个数组的长度。我的错误在哪里?这一切都取决于异步吗?
对我来说似乎是这样,数据是可用的,我可以打印它们,但它不是一个数组。这可能吗?
答案 0 :(得分:3)
那不是数组,its an object。对象没有内置长度属性。如果将对象的长度定义为其enumerable keys数组的长度,则可以执行
Object.keys(data).length