I have a component that is supposed to retrieve data from a service.
Here is my component:
@Component({
templateUrl: 'app/dashboard/useraccount/firstname/useraccount-firstname.component.html',
directives: [ROUTER_DIRECTIVES],
pipes: [TranslatePipe]
})
export class UserAccountFirstNameComponent implements OnInit {
currentUserAccount:Object;
errorMessage:string;
constructor(private userAccountService:UserAccountService) {
}
ngOnInit() {
this.userAccountService.getCurrentUserAccount()
.subscribe(
param=> this.currentUserAccount = param,
error => this.errorMessage = <any>error
);
}
updateFirstName() {
this.userAccountService.updateFirstName(this.currentUserAccount);
}
}
Here is the corresponding service:
@Injectable()
export class UserAccountService {
constructor(private http:Http) {
}
getCurrentUserAccount():Observable<Object> {
return this.http.get('/api/useraccount')
.map(this.mapUserAccount)
.catch(this.handleError);
}
updateFirstName(currentUserAccount) {
this.http.patch('/api/useraccount/firstname/' + currentUserAccount.firstName, null);
}
private mapUserAccount(res:Response) {
console.log(res.json());
return res.json();
}
private handleError(error:any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg = error.message || 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
Here is how the provider for the UserAccountService
:
bootstrap(MainComponent, [ROUTER_PROVIDERS,
HTTP_PROVIDERS,
TRANSLATE_PROVIDERS,
SessionService,
UserAccountService,
TranslateService,
provide(RequestOptions, {useClass: ApplicationRequestOptions}),
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(TranslateLoader, {
useFactory: (http:Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
deps: [Http]
})]);
Here is the relevant part from the template:
<input type="text"
ngControl="firstName"
#firstName="ngForm"
required
minlength="2"
maxlength="35"
pattern_="FIRST_NAME_PATTERN"
[(ngModel)]="currentUserAccount.firstName"
placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| translate }}"
class="form-control"/>
The issue is that by the time the template is rendered, currentUserAccount
is still undefined
in ngModel...
Can anyone please help?
P.S. I am puzzled as my use case (having a component calling a service method that uses http) is very similar to the angular sample provided here: http://plnkr.co/edit/DRoadzrAketh3g0dskpO?p=preview