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.
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.
UPDATE I found out the reason is because the response is an array of objects. 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?
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.
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); }
}