【问题标题】:"ERROR TypeError: Cannot read property '...' of undefined" in Angular 2 [duplicate]Angular 2中的“错误类型错误:无法读取未定义的属性'...'”
【发布时间】:2017-10-11 14:20:50
【问题描述】:

当我通过我的服务检索数据时,我的 Angular 2 脚本的标题出现错误,但页面组件仍在使用 {{ bedriften }} 显示信息,即使我收到错误。我不知道我做错了什么。当我调用 console.log(this.bedriften) 时,它是未定义的,但会显示在页面上。我不确定如何在页面显示给用户之前正确加载信息(我的意思是 this.bedriften 被填充)

我的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

@Injectable()
export class HendingService {
alleHendingar: any;
data: any;
constructor(private http: Http) { }
bed: any;

hentHendingar() {
return this.http.get("http://ekstremedia.no/rapporter/allehendingar.json")
  .map(res => res.json()); 
}
hentBedrift(bed) {
  return this.http.get("http://localhost:81/vossapp/get/bedrift/"+bed)
  .map(res => res.json()); 
  }  
}

我的页面,我得到错误:

import { Component, OnInit, AfterContentInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HendingService } from '../../hending-service.service';

@Component({
  selector: 'app-bedriftside',
  templateUrl: './bedriftside.component.html',
  styleUrls: ['./bedriftside.component.scss'],
  providers: [HendingService]
})

export class BedriftsideComponent implements OnInit {
 id: number;
 private sub: any;
 bedriften: any;
 constructor(private route: ActivatedRoute, private hs: HendingService) { }

ngOnInit() {

    this.sub = this.route.params.subscribe(params => {
       this.id = params['id']; 
    });  

   this.hs.hentBedrift(this.id)
    .subscribe(data => {
       this.bedriften = data
  });    
    console.log(this.bedriften);  // undefined
  }

}

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

    您将 console.log 放在订阅之外,一旦收到响应,您应该能够访问它

      this.hs.hentBedrift(this.id)
        .subscribe(data => {
           this.bedriften = data;
           console.log(this.bedriften); 
      });   
    

    您还需要在模板中使用安全导航运算符检查值是否存在

    <h1> {{bedriften?.title}}</h1>
    

    【讨论】:

    • 但是,在页面组件上,我执行 {{bedriften.title}} 并在控制台中收到此错误消息:错误类型错误:无法读取未定义的属性“标题”。但在页面上它显示的标题正确。它有效,但显然我做错了什么。
    • 您可以使用安全导航运算符 {{bedriften?.title}}
    • 是的!这是一种常见的做法,因为您正在进行异步调用并且必须等待响应
    • 作为一个拥有 55k+ 代表并且通常在 angular 标签中回答的人,您应该意识到这是一个常见问题。将用户重定向到现有资源@Sajeetharan
    • 这不是一个常见的问题,评论前请阅读整个 cmets
    猜你喜欢
    • 2021-12-16
    • 2021-11-05
    • 1970-01-01
    • 2019-04-15
    • 2018-11-21
    • 2020-05-25
    • 2019-03-13
    • 2018-08-29
    • 2019-06-28
    相关资源
    最近更新 更多