【问题标题】:Get response doesn't render in Angular 2 code获取响应不会在 Angular 2 代码中呈现
【发布时间】:2017-09-30 22:27:22
【问题描述】:

我正在尝试呈现发布请求结果。后端工作正常。但是,不可能像这样显示结果:

@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>

【问题讨论】:

    标签: javascript angular angular2-template


    【解决方案1】:

    您的模板应该使用 *ngIf 而不是 ng-if

    <div *ngIf="invoice">
            <span>{{ invoice?.invoiceType | async }}</span>
     </div>
    

    【讨论】:

    • 不幸的是它没有帮助。该字段未呈现。
    • 我在问题的末尾添加了呈现的 html 元素
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多