簡體   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