TypeError:未定义不是对象(TS)

时间:2018-10-20 22:59:34

标签: javascript typescript jqxhr

我正在尝试将响应数组设置为我创建的接口(ApiPosts []) 在尝试将帖子var更新到响应数组时遇到了一个奇怪的错误。 TypeError: undefined is not an object (evaluating 'this.posts = resText')

现在,响应是一个JSON对象数组。当我console.log(res)时,我得到了预期的对象阵列 代码如下:

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
}

这是responseText即时获取示例:

[{
    "_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
}]

如果有任何区别,请立即在角度6上进行

1 个答案:

答案 0 :(得分:0)

在方法中使用function时,this引用的不是当前类see here

  • 在浏览器中是window
  • 在节点中为global
  • 在严格模式下,它是undefined,除非作为方法调用:
    • window.xxx()

例如,请参见此代码段,其中一个输出undefined,另一个输出window

'use strict'

function abc() { console.log(this) }

abc() // outputs undefined
window.abc() // outputs the window object

现在,如果我们删除strict,则它们都将输出窗口:

function abc() { console.log(this) }

abc() // outputs the window object
window.abc() // outputs the window object

您需要做的是在方法本身中创建一个引用,然后在函数中使用该引用,如下所示:

ngOnInit() {

  // Your other stuff here...

  let $this = this;
  function setRes(resText) {
    $this.posts = resText;
  }
}