我正在尝试渲染一个帖子请求结果。后端工作正常。但是,无法显示如下结果:
@Component({
moduleId: module.id,
providers: [InvoiceService],
template: `
<div ng-if="invoice">
<span>{{ invoice?.invoiceType | async }}</span>
</div>
`
})
上面的代码可能有错误。请求响应是异步获取的,但似乎在结果可用之前呈现“模板” - html元素为空。
其他代码经过仔细检查,似乎运行良好,但对于理解可能很重要:
export class InvoiceDetail implements OnInit {
private invoice: Invoice;
private errorMessage: string;
constructor(private invoiceService: InvoiceService, private route: ActivatedRoute) {
}
ngOnInit() {
console.log('On init invoice');
this.getInvoice();
}
getInvoice() {
const id: number = this.route.snapshot.params["id"];
this.invoiceService.getInvoice(id).subscribe(
(invoiceResp: Invoice) => this.invoice = invoiceResp);
console.log("Id: " + id);
}
}
发票类:
export class Invoice {
constructor(
public invoiceNumber: string,
public creationDate: string,
public invoiceType: string
) { }
}
服务方法:
getInvoice(id:number): Observable<Invoice> {
return this.http.get(this.invoiceUrl+id)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
非常感谢任何想法和建议。
编辑: 这是渲染的html元素(我将ng-if更改为* ngIf)
<ng-component>
<!--template bindings={
"ng-reflect-ng-if": "[object Object]"
}--><div>
<span></span>
</div>
</ng-component>
答案 0 :(得分:0)
您的模板应使用 *ngIf
而不是 ng-if
,
<div *ngIf="invoice">
<span>{{ invoice?.invoiceType | async }}</span>
</div>