我试图从官方教程开始一个项目,我在Angular2应用程序中注入服务时出现问题。一切顺利,直到我添加服务。以下是文件:
app.component.ts
import { Component, OnInit } from '@angular/core';
import { client } from './client/client';
import { clientService } from './client/client.service';
@Component({
selector: 'my-app',
template: `
<nav>
<h1>{{title}}</h1>
<h2>client n° {{client.id}}</h2>
</nav>
<client-detail [client]="client"></client-detail>
`,
providers: [clientService]
})
export class AppComponent implements OnInit {
title = "client gendarmerie";
client: client;
constructor(private clientService: clientService) { }
getclient(): void {
this.clientService.getclient().then(client_eg => this.client = client_eg);
}
ngOnInit(): void {
this.getclient();
}
}
服务/ client.service
import { Injectable } from '@angular/core';
import { client } from './client';
import { client_EG } from './mock-client';
@Injectable()
export class clientService {
getclient(): Promise<client> {
return Promise.resolve(client_EG);
}
}
的客户机/模拟客户端
import { client } from './client';
export const client_EG: client = {
id:parseInt('10243'),
contact: {
phone: parseInt('0606060606'),
access: ["Localisation", "chat", "picture"]
},
};
没有服务,一切都很顺利。以下是我在尝试启动应用时遇到的错误:
core.umd.js:3462 EXCEPTION: Error in ./AppComponent class AppComponent
- inline template:3:12 caused by: Cannot read property 'id' of undefinedErrorHandler.handleError @ core.umd.js:3462(anonymous function) @ core.umd.js:6860ZoneDelegate.invoke @ zone.js:203NgZoneImpl.inner.inner.fork.onInvoke @ core.umd.js:6242ZoneDelegate.invoke @ zone.js:202Zone.run @ zone.js:96(anonymous function) @ zone.js:462ZoneDelegate.invokeTask @ zone.js:236NgZoneImpl.inner.inner.fork.onInvokeTask @ core.umd.js:6233ZoneDelegate.invokeTask @ zone.js:235Zone.runTask @ zone.js:136drainMicroTaskQueue @ zone.js:368ZoneTask.invoke @ zone.js:308 core.umd.js:3464 ORIGINAL EXCEPTION: Cannot read property 'id' of undefined
答案 0 :(得分:0)
由于视图上的初始更改检测标记,它正在尝试评估client.id
表达式,其中客户端值为undefined
。因为getclient
方法的承诺尚未得到解决。
您可以使用client?.id
之类的Elvis运算符,然后使用ngIf
指令隐藏client-detail
组件到client
对象的填充
<强>标记强>
<nav>
<h1>{{title}}</h1>
<h2>client n° {{client?.id}}</h2>
</nav>
<client-detail *ngIf="client" [client]="client"></client-detail>