Reputation: 4503
NET Core and Angular 2 application. I have successfully communicated with a web API controller and can log the object in the console.
However when I attempt to log the component in the ts file or access its properties with the [(ngModel)] I am unsuccessful.
Any advice on how to successfully access the object properties in the HTML would be great thanks. Here is my code:
user.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Http, Response, Headers } from '@angular/http';
import { APP_CONFIG, IAppConfig } from './app.config';
import { Component, Inject } from '@angular/core';
@Injectable()
export class UserService {
constructor(private http: Http, @Inject(APP_CONFIG) private config: IAppConfig) { }
//SUCCESSFULLY LOG JSON OBJECT HERE
public getCurrentUser = (): Observable<any> => {
return this.http
.post(this.config.apiEndpoint + "currentUser")
.map((response: Response) => <any>response.json())
.do(x => console.log(x));
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../../user.service';
import { AngUser } from '../../ang-user';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'home-page',
templateUrl: './app/components/home/home.component.html',
providers: [UserService]
})
export class HomeComponent implements OnInit {
constructor(public userService: UserServicer) { }
public value: any;
showObject(): void {
console.log(this.value.id);
console.log(this.value.userName);
}
ngOnInit(): void {
this.userService.getCurrentUser()
.subscribe(data => this.value = data,
error => console.log(error),
() => console.log('Get User complete!'));
this.showObject();
}
}
home.component.html
<!-- THIS FAILS TO SHOW ANYTHING -->
My Values: <ul>
<li [(ngModel)]="value">
<span>{{value.id}} {{value.userName}}</span>
</li>
</ul>
Upvotes: 1
Views: 872
Reputation: 25
<!-- if u get only one object -->
<!--this.value = [{ id: 1, name: 'pbt1' }];-->
My Values: <ul>
<li>
<span>{{value[0].id}} {{value[0].name}}</span>
<input [(ngModel)]="value[0].name" />
</li>
</ul>
<!-- if u get more than one -->
<!--this.value = [{ id: 1, name: 'pbt1' }, { id: 2, name: 'pbt2' },{ id: 3, name: 'pbt3' }];-->
My Values: <ul >
<li *ngFor="let v of value">
<span>{{v.id}} {{v.name}}</span>
<input [(ngModel)]="v.name" />
</li>
</ul>
Upvotes: 0
Reputation: 222702
Remove [(ngModel)]="value"
from li
<li >
<span>{{value.id}} {{value.userName}}</span>
</li>
Upvotes: 1