如何在Angular 2中等待渲染组件直到所有数据都是gathert

时间:2017-02-01 14:34:22

标签: angular asynchronous typescript

我尝试了很多东西让ngModel在我的编辑页面中工作,但它给了我一个错误。错误发生,因为ngModel在贷款之前尝试获取数据。请参阅下面的代码。

ProductEditComponent

import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Location } from '@angular/common';

import { Product } from './../shared/product.model';
import { ProductService } from './../shared/product.service';

@Component({
    selector: 'product-edit',
    template: require('./product-edit.component.html'),
    providers: [ProductService]
})

export class ProductEditComponent implements OnInit {
    product: Product;
    name2: boolean = false;

    constructor(
        private productService: ProductService,
        private route: ActivatedRoute,
        private location: Location,
        private router: Router
    ) { }

    ngOnInit(): void {
        var test = this.route.params
            .switchMap((params: Params) => this.productService.getProduct(+params['id']))
            .subscribe(product => this.product = product).closed;
            console.log(test);
        if (test['closed']) {
            this.name2 = true;
        }
    }

    goBack(): void {
        this.location.back();
    }

    onSave(): void {
        this.router.navigate(['product-edit', this.product]);
    }
}

ProducEdit HTML

<div class="product-edit">
    <h2>Edit: {{product?.name}}</h2>
    <div class="form-group row" *ngIf="name2">
        <label for="name" class="col-2 col-form-label">Name</label>
        <div class="col-10">
            <input class="form-control" id="name" [(ngModel)]="name2" placeholder="" />
        </div>
    </div>
</div>

我怎么能等到加载数据然后渲染我的组件?

3 个答案:

答案 0 :(得分:4)

您甚至可以在实例化ProductEditComponent之前使用路由器为您预加载产品数据。

更具体地说,您需要在路线声明中使用Resolve防护,例如:

{
  path: 'product/:productId',
  component: ProductEditComponent,
  resolve: { product: ProductResolver }
}

其中ProductResolver是一个自定义服务,用于加载ID为productId的产品。

查看官方文档,其中包含一个完整示例,说明如何声明路由,如何实现解析以及如何检索组件内的预取数据:https://angular.io/docs/ts/latest/guide/router.html#resolve-guard

答案 1 :(得分:3)

我只能假设它与未实例化的产品对象有关。像这样使用* ngIf。无需初始化为null,因为null是&#39; falsy&#39;

<div class="product-edit" *ngIf="product">
<h2>Edit: {{product?.name}}</h2>
<div class="form-group row" *ngIf="name2">
    <label for="name" class="col-2 col-form-label">Name</label>
    <div class="col-10">
        <input class="form-control" id="name" [(ngModel)]="name2" placeholder="" />
    </div>
</div>

答案 2 :(得分:1)

首先将产品初始化为null

product: Product = null;

第二次将* ngIf添加到html

<div class="product-edit" *ngIf="product != null">
    <h2>Edit: {{product.name}}</h2>
    <div class="form-group row" *ngIf="name2">
        <label for="name" class="col-2 col-form-label">Name</label>
        <div class="col-10">
            <input class="form-control" id="name" [(ngModel)]="name2" placeholder="" />
        </div>
    </div>
</div>