在我的Angular 2应用程序中,出现错误:
无法读取undefined的属性'title'。
这是一个非常简单的组件,只是试图在这里工作。它击中我的API控制器(奇怪地多次),它似乎在返回一个对象后点击回调。我的console.log输出了我期望的对象。这是完整的错误:
TypeError: Cannot read property 'title' of undefined
at AbstractChangeDetector.ChangeDetector_About_0.detectChangesInRecordsInternal (eval at <anonymous> (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:10897:14), <anonymous>:31:26)
at AbstractChangeDetector.detectChangesInRecords (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8824:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8807:12)
at AbstractChangeDetector._detectChangesInViewChildren (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8877:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8811:12)
at AbstractChangeDetector._detectChangesContentChildren (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8871:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8808:12)
at AbstractChangeDetector._detectChangesInViewChildren (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8877:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8811:12)
at AbstractChangeDetector.detectChanges (http://localhost:55707/lib/angular2/bundles/angular2.dev.js:8796:12)
服务(about.service.ts):
import {Http} from 'angular2/http';
import {Injectable} from 'angular2/core';
import {AboutModel} from './about.model';
import 'rxjs/add/operator/map';
@Injectable()
export class AboutService {
constructor(private _http: Http) { }
get() {
return this._http.get('/api/about').map(res => {
console.log(res.json()); // I get the error on the line above but this code is still hit.
return <AboutModel>res.json();
});
}
}
组件(about.component.ts):
import {Component, View, OnInit} from 'angular2/core';
import {AboutModel} from './about.model';
import {AboutService} from './about.service';
import {HTTP_PROVIDERS} from 'angular2/http';
@Component({
selector: 'about',
providers: [HTTP_PROVIDERS, AboutService],
templateUrl: 'app/about/about.html'
})
export class About implements IAboutViewModel, OnInit {
public about: AboutModel;
constructor(private _aboutService: AboutService) {}
ngOnInit() {
this._aboutService.get().subscribe((data: AboutModel) => {
this.about = data;
});
}
}
export interface IAboutViewModel {
about: AboutModel;
}
的index.html
<script src="~/lib/systemjs/dist/system.src.js"></script>
<script src="~/lib/angular2/bundles/router.js"></script>
<script src="~/lib/angular2/bundles/http.js"></script>
<script src="~/lib/angular2/bundles/angular2-polyfills.js"></script>
<script src="~/lib/angular2/bundles/angular2.dev.js"></script>
<script src="~/lib/es6-shim/es6-shim.js"></script>
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
},
map: {
rxjs: "lib/rxjs"
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
答案 0 :(得分:53)
请在下次包含您的观点和型号(app / about / about.html和about.model)。
如果要返回数组,可以使用asyncPipe,它“订阅Observable或Promise并返回它发出的最新值。当发出新值时,异步管道标记要检查更改的组件“因此视图将使用新值进行更新。
如果要返回基本类型(字符串,数字,布尔值),还可以使用asyncPipe。
如果你要返回对象,我不知道有什么方法可以使用asyncPipe ,我们可以使用异步管道和{{3 } ?.
如下:
{{(objectData$ | async)?.name}}
但这看起来有点复杂,我们必须为我们想要显示的每个对象属性重复这一点。
作为注释中提到的@pixelbits,您可以subscribe()
到控制器中的observable并将包含的对象存储到组件属性中。然后在模板中使用安全导航操作符或NgIf:
service.ts
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import 'rxjs/add/operator/map'; // we need to import this now
@Injectable()
export class MyService {
constructor(private _http:Http) {}
getArrayData() {
return this._http.get('./data/array.json')
.map(data => data.json());
}
getPrimitiveData() {
return this._http.get('./data/primitive.txt')
.map(data => data.text()); // note .text() here
}
getObjectData() {
return this._http.get('./data/object.json')
.map(data => data.json());
}
}
app.ts
@Component({
selector: 'my-app',
template: `
<div>array data using '| async':
<div *ngFor="let item of arrayData$ | async">{{item}}</div>
</div>
<div>primitive data using '| async': {{primitiveData$ | async}}</div>
<div>object data using .?: {{objectData?.name}}</div>
<div *ngIf="objectData">object data using NgIf: {{objectData.name}}</div>`
providers: [HTTP_PROVIDERS, MyService]
})
export class AppComponent {
constructor(private _myService:MyService) {}
ngOnInit() {
this.arrayData$ = this._myService.getArrayData();
this.primitiveData$ = this._myService.getPrimitiveData();
this._myService.getObjectData()
.subscribe(data => this.objectData = data);
}
}
数据/ array.json
[ 1,2,3 ]
数据/ primitive.json
Greetings SO friends!
数据/ object.json
{ "name": "Mark" }
输出:
array data using '| async':
1
2
3
primitive data using '| async': Greetings SO friends!
object data using .?: Mark
object data using NgIf: Mark
答案 1 :(得分:29)
看起来您在视图about.title
中引用了about.html
,但about
变量仅在http
请求完成后才会实例化。要避免此错误,您可以使用about.html
<div *ngIf="about"> ... </div>
答案 2 :(得分:17)
之前的答案是正确的。 在模板中使用变量之前,您需要检查变量是否已定义。使用HTTP请求需要时间来定义它。使用* ngIf来检查。示例由角度https://angular.io/docs/ts/latest/tutorial/toh-pt5.html提供 示例是http://plnkr.co/edit/?p=preview
<div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
您可以查看app / hero-detail.component [ts和html]