Angular2 ng For select在模型更改之前不会更新

时间:2016-02-15 18:11:58

标签: service angular

我有一个带有ngFor的简单选择,并且选择框为空,直到我输入其中一个字段然后它神奇地显示数据,即使我知道它先前完成了数据调用。

我的观点

<div class="form-group col-md-3">
    <label for="payerId">PayerId</label>
    <select class="form-control">
        <option *ngFor="#item of model.payers">{{item.HealthPlanName}}</option>
    </select>
</div>
<div class="form-group col-md-3">
    <label for="providerType">Provider Type</label>
    <input type="text" class="form-control" [(ngModel)]="model.providerType"/>
</div>

我的组件

import {Component, Injectable, OnInit, View} from "angular2/core";
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgForm, NgFormControl, NgFor} from "angular2/common";
import {CoverageService} from "../../services/coverage/coverage.services";
import "rxjs/Rx";

@Component({
    selector: "coverage",
    providers: [CoverageService]
})
@View({
    templateUrl: "/Scripts/appScripts/components/coverage/coverage.html",
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES, NgForm, NgFormControl, NgFor, PayerSelector]
})
export class CoverageComponent implements OnInit {
    model = new CoverageRequest();
    constructor(private coverageService: CoverageService) {}
    ngOnInit() {
        this.getPayers();
    }
    getPayers() {
        this.coverageService.getPayers()
            .subscribe(resp => {
                this.model.payers = resp;
            });
    }  
}

真的挠我的头。

以下是我正在使用的库:

"dependencies": {
"angular2": "2.0.0-beta.0",
"systemjs": "^0.19.20",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.0",
"zone.js": "0.5.10"
}

我的服务

import {Http, Response} from "angular2/http";
import {Injectable} from "angular2/core";
import {COVERAGE_BASE} from "../../config";
import "rxjs/Rx";

@Injectable()
export class CoverageService {
    constructor(public http: Http) {

    }

    getPayers(): any {
        return this.http.get(COVERAGE_BASE + "/Payers")
            .map((response: Response) => response.json());
    }
}

数据

[{
    "Id": 3817,
    "ProviderId": 2,
    "ApiPayerId": "00028",
    "HealthPlanName": "Georgia Medicaid",
    "Type": null,
    "PayerSynonyms": null
}, {
    "Id": 3818,
    "ProviderId": 2,
    "ApiPayerId": "00143",
    "HealthPlanName": "J. F. Molloy and Associates Inc.",
    "Type": null,
    "PayerSynonyms": null
}]

1 个答案:

答案 0 :(得分:0)

尝试在ngOnInit中启动模型,而不是直接在类中启动。您将需要在视图中使用elvis运算符,因为模型最初将是未定义的。在此处阅读有关elvis运算符的更多信息:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#sts=The%20Elvis%20operator%20(%20%3F.%20)%20and%20null%20property%20paths

我不完全确定,但我认为它应该有效。