我按照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,
) {}
}
mock.data.ts
import { MooseCode } from './moose.code';
export const MOCK_DATA: MooseCode[] = [
{
'firstVariable': 'any',
'secondVariable': 'any',
}
];
我尝试使用以下方法访问模板中的firstVariable
和secondVariable
:
{{currentThing.firstVariable}}
和
{{currentThing[0].firstVariable}}
什么都行不通!我做错了什么?
答案 0 :(得分:0)
您的服务“getHomePageCodeSlowly
无法解析。尝试:
setTimeout(resolve(MOCK_DATA), 2000))
然后@ component getCode()
currentThing [0] .firstVariable或secondvariable
答案 1 :(得分:0)
@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>