我从服务器获取数据但数组长度未定义

时间:2018-02-19 18:31:53

标签: angular

我使用以下代码。

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);
                    }
                }
            );
    }
}

控制台中的输出是:

enter image description here

我每次都得到一个数据数组,但我不能得到这个数组的长度。我的错误在哪里?这一切都取决于异步吗?

对我来说似乎是这样,数据是可用的,我可以打印它们,但它不是一个数组。这可能吗?

1 个答案:

答案 0 :(得分:3)

那不是数组,its an object。对象没有内置长度属性。如果将对象的长度定义为其enumerable keys数组的长度,则可以执行

Object.keys(data).length