【问题标题】:TypeError: undefined is not an object (TS)TypeError: undefined is not an object (TS)
【发布时间】:2019-03-25 10:23:16
【问题描述】:

我正在尝试将响应数组设置为我创建的接口 (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
}]

如果有什么不同的话,我会在 Angular 6 上做

【问题讨论】:

  • setRes 函数在ngOnInit 中定义,因此this 未定义。您需要它作为组件的方法。此外,您没有使用 Angular 发出 HTTP 请求的方式(至少应该通过服务,最好使用HttpClient)。

标签: javascript typescript jqxhr


【解决方案1】:

在方法中使用function 时,this 引用当前类see here 之外的其他内容。

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

查看这个 sn-p 例如一个输出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;
  }
}

【讨论】:

  • 太棒了!非常感谢!,它的工作,但如果你有一个更简单的方法来做同样的事情的建议,我会很高兴听到,(分配获取响应接口变量)
  • 更简单的方法是将setRes 作为它自己的方法而不是方法内部的函数
猜你喜欢
  • 2020-08-15
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 2023-02-18
  • 2019-03-11
相关资源
最近更新 更多