数据不会附加到angular2中的模板

时间:2016-08-22 13:32:13

标签: angular typescript

我正在尝试将数据附加到我的模板

  @Injectable()
  export class GetAllList {
   str = localStorage.getItem('social');
   loc = JSON.parse(this.str);
   id = this.loc.profile_id;
   private _productUrl = 'http://localhost/a2server/index.php/profile/editProfile/' + this.id;

  constructor(private _http: Http) { }
     getList(): Observable<IDetails[]> {
     return this._http.get(this._productUrl)
        .map((response: Response) => {
         return <IDetails[]>response.json().data[0];
        });
}

}

我订阅如下,

this._profileservice.getList()
 .subscribe(details => this.details = details);console.log(this.details);

我的模板,

<div class="nopadding col-sm-12">

<div class="col-sm-12 nopadding profile">
    <div class="col-sm-12 formpaddingcss">
        <h3 class="headingfontcss">MY PROFILE</h3>
    </div>
    <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin col-sm-12 formpaddingcss" name="template-contactform"
        novalidate="novalidate">


        <div class="form-process"></div>
        <div class="col_half">
            <label for="template-contactform-name">First Name <small>*</small></label>
            <div class="input-group divcenter">
                <span class="input-group-addon  noradius"><i class="icon-user iconcolorcss"></i></span>
                <input type="email" tooltip="Enter Firstname" [tooltipDisabled]="false" [tooltipAnimation]="true"
                    tooltipPlacement="top" name="widget-subscribe-form-email" class="form-control required email formcontrolheight"
                    [formControl]="form.controls['firstname']" [(ngModel)]="details.firstname" placeholder="First Name" required>
            </div>
        </div>

    </form>

来自后端的数据,

 [{profile_id: "1", firstname: "Sachin", lastname: "Tendulkar", profilename: "sachin tendulkar",…}]

我的错误是

TypeError: Cannot read property 'firstname' of undefined

我一直在尝试但没有结果,有人可以解释我的问题

1 个答案:

答案 0 :(得分:2)

Angular尝试在_http.get的响应到来之前绑定您的表单。

使用

<form *ngIf="details" [formGroup]

延迟呈现表单直到数据到达。

通常安全导航操作员details?.firstname非常方便,但目前不能用于双向绑定

支持

[(ngModel)]="details?.firstname"

将其更改为

[ngModel]="details?.firstname" (ngModelChange)="details.firstname = $event"

会让它发挥作用,但我认为在你的情况下,第一个建议是更合适。