简体   繁体   English

静态调用后未更新Angular 2 ngModel

[英]Angular 2 ngModel not updated after restful call

I have a simple user component that retrieve user's firstname and lastname. 我有一个简单的用户组件,可以检索用户的名字和姓氏。 When user click on the submit button, it will make a restful call and retrieve the details and pass back to my user object. 当用户单击“提交”按钮时,它将进行一次安静的通话,并检索详细信息并传递回我的用户对象。 However, this is not happening at the moment and I'm not sure what went wrong. 但是,目前还没有发生这种情况,我不确定出了什么问题。

When I initiate the model during init manually, the form will display the user's data correctly. 当我在初始化过程中手动启动模型时,表单将正确显示用户的数据。 If I retrieve and assign the values back to the form from the Rest API call, the form is not being updated. 如果我从Rest API调用中检索值并将其分配回表单,则不会更新该表单。

I've verified the data is being retrieved correctly, my diagnostic method also shows the model has the response data mapped correctly. 我已经验证了可以正确检索数据,我的诊断方法还显示了模型已正确映射了响应数据。 I've tried the zone.run but the form is not updated too. 我已经尝试过zone.run,但是表单也没有更新。

UPDATE I found out the reason is because the response is an array of objects. 我发现UPDATE的原因是因为响应是对象数组。 Changing the following has resolved the issue. 更改以下内容已解决了该问题。

this.model = new User().fromJSON(user)[0];

I'm not sure whether there is any way to ensure my service always return an JSON object instead of an array of objects? 我不确定是否有任何方法可以确保我的服务始终返回JSON对象而不是对象数组?

userservice.ts userservice.ts

 return this.http.post('http://ng2nodejs.azurewebsites.net/api/user', data , {
            headers: authHeader
        })
        .map((response: Response) => { return response.json()});

My user component - The diagnostic is displaying the data correctly though 我的用户组件 -诊断程序虽然正确显示了数据

{{diagnostic}}

<h1>User Form</h1>
<form (ngSubmit)="f.form.valid && getUser()" #f="ngForm" >                        
    <div class="form-group">
       <label for="firstname">First Name</label>
       <input type="text" id="firstname" [(ngModel)]="model.firstname" name="firstname" >
    </div>
    <div class="form-group">
       <label for="lastname">Last Name</label>
       <input type="text" id="lastname" [(ngModel)]="model.lastname" name="lastname" >
    </div>  

    <button>Submit</button>                
</form>

The user model , the fromJSON method is to convert the response to my user model. 用户模型 fromJSON方法将响应转换为我的用户模型。

export class User {
  username: string;      
  firstname: string;
  lastname: string; 

  fromJSON(json) {
        for (var propName in json)
            this[propName] = json[propName];
        return this;
    }
}

My component 我的组件

 import { Component, NgZone } from '@angular/core';
 import { User } from '../auth/user';
 import { UserService } from '../auth/user.service';

 @Component({
   moduleId: module.id,
   selector: 'app-first',
   templateUrl: './first.component.html',
   styleUrls: ['./first.component.css'],

 })
 export class FirstComponent {
     constructor(private userService: UserService, private zone:NgZone) { }  
     model =  new User();    
     getUser() {             
          this.userService
             .getUser('User123')
             .subscribe((user: Object) => {
                  this.zone.run(() => { 
                     this.model = new User().fromJSON(user);     
                  });  
             });
     }

     get diagnostic() { return JSON.stringify(this.model); }
 }

I don't know if this solves your issue, but I would give some pointers here. 我不知道这是否可以解决您的问题,但在此我会给出一些建议。

If you really don't have a reason to use Classes, I would suggest you'd move to interfaces: 如果您确实没有使用类的理由,建议您改用接口:

export interface User {
  username: string;      
  firstname: string;
  lastname: string; 
}

and NgZone shouldn't be needed here. 在这里不需要NgZone。

export class FirstComponent {
  constructor(private userService: UserService) { }  
  model: User = {};   

  getUser() {             
    this.userService
      .getUser('User123')
      .subscribe((user: Object) => {
         this.model = user;
      });
  }
}

And if you have control of your API, why not return the newly created user when you actually create the new User, so that you do not need to make a separate http call to get the user. 而且,如果您可以控制API,那么为什么在实际创建新用户时不返回新创建的用户,这样就无需进行单独的http调用来获取用户。

With the above at least this plunker seems to be working well. 至少通过以上操作, 此插件似乎运行良好。 The properties are a bit different, since I use mockbackend here. 这些属性有些不同,因为我在这里使用了模拟后端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM