繁体   English   中英

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

[英]TypeError: undefined is not an object (TS)

我试图将响应数组设置为我创建的接口(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上做它是否有任何区别

在方法中使用functionthis引用的不是当前类,而是参见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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM