首页 / JAVASCRIPT / javascript – Angular 2:TypeError:在AppComponent @ 4中的[{{thing.title}}中未定义l_thing0:44]
javascript – Angular 2:TypeError:在AppComponent @ 4中的[{{thing.title}}中未定义l_thing0:44]
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – Angular 2:TypeError:在AppComponent @ 4中的[{{thing.title}}中未定义l_thing0:44],小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1646字,纯文字阅读大概需要3分钟。
内容图文
![javascript – Angular 2:TypeError:在AppComponent @ 4中的[{{thing.title}}中未定义l_thing0:44]](/upload/InfoBanner/zyjiaocheng/714/2575e75d9a8846239e7c2f540c69b725.jpg)
我的应用程序中出现了一个奇怪的错误.它应该从对象打印出{{thing.title}},但它在控制台中显示错误:
EXCEPTION: TypeError: l_thing0 is undefined in [{{thing.title}} in AppComponent@4:44]
我不确定l_thing0来自哪里.如果我尝试在页面中显示{{thing}},则会显示[object Object].如果我尝试JSON.stringify(this.thing)(参见showObj()函数),它会正确显示字符串化对象.但是如果我尝试访问像{{thing.title}}这样的属性,我会得到l_thing0未定义的错误.
这是app.component.ts:
import {Component, OnInit} from 'angular2/core';
import {Thing} from './thing';
import {ThingService} from './thing.service';
import {SubThingComponent} from "./subthing.component";
@Component({
selector: 'thing-app',
template: `
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>{{thing.title}} <a href="#" (click)="showObj()" class="btn btn-default">Show Stringified Obj</a></h1>
<subthing></subthing>
</div>
</div>
</div>
`,
styles:[`
`],
directives: [SubThingComponent],
providers: [ThingService]
})
export class AppComponent implements OnInit {
constructor(private _thingService: ThingService) { }
public thing: Thing;
showObj() {
// This correctly shows the stringified object
alert(JSON.stringify(this.thing));
}
getThing() {
this._thingService.getThing().then(thing => this.thing = thing);
// This correctly logs the object
setTimeout(() => {console.log('thing', this.thing)}, 5000);
}
ngOnInit() {
this.getThing();
}
}
有任何想法吗?
解决方法:
问题是,第一次加载页面时,事物仍未定义,稍后会异步设置为实际值,因此第一次尝试访问该属性时,它将引发异常.的? elvis运算符是nullcheck的快捷方式:
{{事?.title伪}}
但它通常是一个最好的想法更高效甚至尝试渲染组件,直到你有真正的对象,通过添加如下:
< h1 * ngIf =“thing”>
到容器.
内容总结
以上是互联网集市为您收集整理的javascript – Angular 2:TypeError:在AppComponent @ 4中的[{{thing.title}}中未定义l_thing0:44]全部内容,希望文章能够帮你解决javascript – Angular 2:TypeError:在AppComponent @ 4中的[{{thing.title}}中未定义l_thing0:44]所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。