[英]TypeError: Cannot read property 'state' of undefined at Object.eval - Service object cannot bind to ngModel in Angular 5
I have an object declared in my service :我在我的服务中声明了一个对象:
public caseDetails = {
partyId: '',
address: {
state: '',
city: '',
zip: '',
street: ''
}
}
I need to bind the objects to a input box.我需要将对象绑定到输入框。 Here is what I could do
这是我能做的
<input type="text" [(ngModel)]="this.serviceObj.caseDetails.partyId">
Here is the what I can't do这是我不能做的
<input type="text" [(ngModel)]="this.serviceObj.caseDetails.address.state">
I could bind if the object declared in my component.如果在我的组件中声明了对象,我可以绑定。 But I can't bind to a service object.
但我无法绑定到服务对象。 Here is the error details:
这是错误的详细信息:
ERROR TypeError: Cannot read property 'state' of undefined at Object.eval [as updateDirectives]
错误 TypeError:无法读取 Object.eval 处未定义的属性“状态”[作为 updateDirectives]
Note: it not recommended way to bind data from service object directly, it's better you get data from service and store in local variable to component and do work on that.注意:不推荐直接从服务对象绑定数据的方法,最好从服务获取数据并将其存储在局部变量中到组件并对其进行处理。 An example:
一个例子:
component.ts :组件.ts :
export class abcComponent implements OnInit {
datafromService:any;
constructor(
public service: DataService
) { }
ngOnInit() {
this.datafromService = service.caseDetails;
}
}
html of component then :组件的 html 然后:
{{datafromService|json}}
{{datafromService.address.state|json}}
<form>
<input name='test' type="text"
[(ngModel)]="datafromService.address.state">
</form>
Service-code there is no change.服务代码没有变化。
Below is working tried and tested at my end.下面是在我这边尝试和测试的工作。
service.ts :服务.ts :
@Injectable()
export class DataService {
public caseDetails = {
partyId: '',
address: {
state: 'mystate',
city: '',
zip: '',
street: ''
}
}
}
component.ts :组件.ts :
@Component({
selector: 'abc',
templateUrl: 'abc.component.html'
})
export class abcComponent {
constructor(
public service: DataService
) { }
}
component.html :组件.html :
{{service.caseDetails|json}}
{{service.caseDetails.address.state|json}}
<form>
<input name='test' type="text"
[(ngModel)]="deskService.caseDetails.address.state">
</form>
There is issue that you used this
, it should be你用
this
有问题,应该是
<input type="text" [(ngModel)]="serviceObj.caseDetails.address.state">
for this to work serviceObj
need to be public
so it will work为此,
serviceObj
需要public
才能正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.