“ERROR TypeError:无法在Angular 2中读取未定义的属性'...'

时间:2017-10-11 04:09:47

标签: angular angular2-services

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

我的服务:

AccessibilityManager accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);

Iterable<AccessibilityServiceInfo> serviceInfoList = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_SPOKEN);

for (AccessibilityServiceInfo serviceInfo : serviceInfoList) {
    //Could get even more specific here if you wanted. IDs have fully qualified package names in them as well.
    if (serviceInfo.getId().endsWith("TalkBackService")) {
        //TalkBack is on do your thing
    }
}

我的页面,我收到错误:

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()); 
  }  
}

1 个答案:

答案 0 :(得分:0)

您将console.log放在订阅之外,您应该能够在收到回复后访问它

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

同样在模板中,您需要使用安全导航操作符

检查值是否存在
<h1> {{bedriften?.title}}</h1>