![](/img/trans.png)
[英]Access Observable<google.maps.GeocoderResult[]> object properties in Angular2
[英]Unable to access Angular2 Service object properties
我遵循Angular2文档为我的应用程序创建服务,但似乎无法访问前端的信息。
当我尝试使用插值访问模板中的firstVariable
和secondVariable
时,得到了[Object object]
。 我决定使用json管道来从对象中很好地读取内容,该方法可以正常工作。 但是,我无法弄清楚为什么我无法访问firstVariable
和secondVariable
。 我收到一个错误,读取cannot read property 'firstVariable' of undefined
。
这是我的代码:
moose.component.ts
import { Component, OnInit } from '@angular/core';
import { MooseService } from './moose.service';
import { MooseCode } from './moose.code';
@Component({
selector: 'moose-selector',
templateUrl: './moose.component.html',
providers: [MooseService]
})
export class MooseComponent implements OnInit {
currentThing: MooseCode[];
getCode(): void {
this._mooseService.getCodeSlowly()
.then(currentThing => this.currentThing = currentThing);
}
ngOnInit() {
this.getCode();
}
constructor(private _mooseService: MooseService) {}
}
moose.service.ts
import { Injectable } from '@angular/core';
import { MooseCode } from './moose.code';
import { MOCK_DATA } from './mock-data';
@Injectable()
export class MooseService {
getCode(): Promise<MooseCode[]> {
return Promise.resolve(MOCK_DATA);
}
getCodeSlowly(): Promise<MooseCode[]> {
return new Promise<MooseCode[]>(resolve =>
setTimeout(resolve, 2000)) // delay 2 seconds
.then(() => this.getCode());
}
}
moose.component.html
<pre>
{{ currentThing | json }}
</pre>
moose.code.ts
export class MooseCode {
constructor(
public firstVariable: any,
public secondVariable: any,
) {}
}
模拟数据
import { MooseCode } from './moose.code';
export const MOCK_DATA: MooseCode[] = [
{
'firstVariable': 'any',
'secondVariable': 'any',
}
];
我尝试使用以下方法访问模板中的firstVariable
和secondVariable
:
{{currentThing.firstVariable}}
和{{currentThing[0].firstVariable}}
没用! 我究竟做错了什么?
您的服务的getHomePageCodeSlowly
解析没有任何价值。 尝试:
setTimeout(resolve(MOCK_DATA), 2000))
然后@ component getCode()
currentThing [0] .firstVariable或secondvariable
@estus方法将起作用- {{currentThing?[0].firstVariable}}
。 但是,如果您不想每次都使用问号,请使用ngIf-这将以相同的方式工作。 因此,例如,假设:
ItemObject = {
id: 1,
name: "something",
anotherProperty: "whatever",
isThisReal: false
}
<div class="item" *ngIf="ItemsObject">
<h1>{{ItemObject.isThisReal}}</h1>
</div>
输出应为: <h1>false</h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.