I'm trying to render a post request result. The backend is working fine. However, it is impossible to display the result like this:
@Component({
moduleId: module.id,
providers: [InvoiceService],
template: `
<div ng-if="invoice">
<span>{{ invoice?.invoiceType | async }}</span>
</div>
`
})
There is probably a mistake in the code above. The request response is get asynchronously, but is seems that the "template" is rendered before the result is available - the html element is empty.
The rest of the code was checked carefully and seems to be working well, but might be important for understanding:
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);
}
}
The invoice class:
export class Invoice {
constructor(
public invoiceNumber: string,
public creationDate: string,
public invoiceType: string
) { }
}
The service methods:
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);
Any ideas and suggestions will be very appreciated.
EDIT: This is the rendered html element (I changed ng-if to *ngIf)
<ng-component>
<!--template bindings={
"ng-reflect-ng-if": "[object Object]"
}--><div>
<span></span>
</div>
</ng-component>
Your template should use *ngIf
not ng-if
,
<div *ngIf="invoice">
<span>{{ invoice?.invoiceType | async }}</span>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.