Im trying to set response array to an interface I have created (ApiPosts[])
And I'm getting this strange error when in trying to update the posts var to the response array.
TypeError: undefined is not an object (evaluating 'this.posts = resText')
Now the response is an array of JSON objects. And when I console.log(res)
i get an expected array of objects
The code is as follows:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { post } from 'selenium-webdriver/http';
import { Injectable } from '@angular/core';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
@Component({
selector: 'app-my-likes',
templateUrl: './my-likes.component.html',
styleUrls: ['./my-likes.component.css']
})
export class MyLikesComponent implements OnInit {
posts:ApiPosts[];
constructor(private http:HttpClient) { }
ngOnInit() {
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var res = JSON.parse(this.responseText);
console.log(res);
setRes(res);
}
});
xhr.open("GET", my url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("x-apikey", my key);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
function setRes(resText) {
this.posts = resText;
console.log(resText);
}
}
}
interface ApiPosts {
_id: string,
address: string,
price: number,
rooms: number,
sqmt: number,
_mock: boolean
}
this is an example of the responseText im getting:
[{
"_id": "5bc98372f27689550002c99d",
"address": "979 Parisian Divide Suite 335\nTonistad, TX 33097",
"price": 1472,
"rooms": 6,
"sqmt": 984,
"_mock": true
}, {
"_id": "5bc98372f27689550002c9a9",
"address": "416 Barbara Dale\nLake Velva, GA 83588",
"price": 2028,
"rooms": 8,
"sqmt": 1518,
"_mock": true
}, {
"_id": "5bc98372f27689550002c9a3",
"address": "3109 Amely Stream\nJohnsonmouth, UT 83874",
"price": 3435,
"rooms": 11,
"sqmt": 1891,
"_mock": true
}]
im doing it on angular 6 if it makes any difference