TypeError:无法读取未定义的属性-但网站可以正常工作-Angular 7

时间:2018-12-19 19:24:05

标签: angular angular7

list::list(const list &rhs) {
    head = tail = nullptr;
    for(node* tmp = rhs.head; tmp!=NULL; tmp=tmp->next) {
        push_back(tmp->val);
    }
    num_elements = rhs.num_elements;
}

list::~list() {
    node *T = head;
    while(T != nullptr)
    {
        node *T2 = T;
        T = T->next;
        delete T2;
    }
    head = nullptr;
    tail = nullptr;
    num_elements = 0;
}

void list::push_back(double elem) {
    node *n = new node;
    n->val = elem;
    if(tail == nullptr)
    {
        head = n;
        tail = head;
    }
    else
    {
        tail->next = n;
        n->prev = tail;
        tail = n;
    }
    num_elements++;
}

void list::push_front(double elem) {
    node *n = new node;
    n->val = elem;
    if(head == nullptr)
    {
        head = n;
        tail = head;
    }
    else
    {
        head->prev = n;
        n->next = head;
        head = n;
    }
    num_elements++;
}
list &list::operator=(const list &rhs) {
    list temp(rhs);
    std::swap(head, temp.head);
    std::swap(tail, temp.tail);
    std::swap(num_elements, temp.num_elements);
    return *this;
}

list::list(list &&rhs) {
    head = rhs.head;
    tail = rhs.tail;
    num_elements = rhs.num_elements;

    rhs.head = nullptr;
    rhs.tail = nullptr;
    rhs.num_elements = 0;
}

list &list::operator=(list &&rhs) {
    this->~list(); // Destroy our current contents
    std::swap(head, rhs.head);
    std::swap(tail, rhs.tail);
    std::swap(num_elements, rhs.num_elements);
    return *this;
}

我的应用程序在浏览器中可以正常显示,但我想了解/修复的Chrome控制台中出现此错误。 控制台发出3次错误,并指向文件/行TypeError: Cannot read property 'city' of undefined ,即CurrentWeatherComponent.html:3

如果我删除<span>{{current.city}}, {{current.country}} </span>,它将给出错误{{current.city}}, 事实是,在浏览器中,应用程序实际上呈现了TypeError: Cannot read property 'country' of undefined城市,current国家,current日期以及current的所有其他属性。 由于错误已在控制台中打印了三遍,但随后呈现的很好,我想这与计时有关吗?

以下代码出于完整性考虑。让我知道是否(和什么)需要发布以获取更多详细信息。

HTML:

current

组件:

current-weather.component.html:
<div>
  <div>
    <span>{{current.city}}, {{current.country}} </span>
    <span>{{current.date | date:'fullDate'}}</span>
  </div>
  <div>
    <img [src]='current.image'>
    <span>{{current.temperature | number: '1.0-0'}}℉</span>
  </div>
  <div>
    {{current.description}}
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

直到weatherService.getCurrentWeather函数发出data的那一刻,this.currentundefined,因此您会在控制台中看到这些错误。

您可以使用{{current?.city}}并对current的所有其他属性执行相同的操作。或者,您可以通过使用current属性来渲染所有使用*ngIf的元素,直到可用为止:

<div *ngIf="current">
  <div>
    <span>{{current.city}}, {{current.country}} </span>
    <span>{{current.date | date:'fullDate'}}</span>
  </div>
  <div>
    <img [src]='current.image'>
    <span>{{current.temperature | number: '1.0-0'}}℉</span>
  </div>
  <div>
    {{current.description}}
  </div>
</div>