2017-04-23 161 views
1

NET Core和Angular 2應用程序。我已經成功與Web API控制器進行通信,並可以在控制檯中記錄對象。Angular 2 [(ngModel)]不起作用

但是,當我嘗試在ts文件中記錄組件或使用[(ngModel)]訪問其屬性時,我不成功。

有關如何成功訪問HTML中的對象屬性的任何建議將非常感謝。這裏是我的代碼:

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> 
+1

控制檯中的任何錯誤? – Alex

+0

出人意料的沒有 – RyeGuy

回答

1

取下[(ngModel)]="value"li

<li > 
    <span>{{value.id}} {{value.userName}}</span> 
</li> 
+0

這沒有效果 – RyeGuy

+0

你在this.value裏面看到了什麼? – Sajeetharan

+0

我已經調整了主件組件來記錄對象。當它運行時,我看到Id和userName,因爲我應該 – RyeGuy

0
<!-- 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> 
+0

請給出一些關於你的代碼的解釋。 –

+0

Working plunker:http://plnkr.co/edit/5vx0tzrfh5Kc7YTU7ixE?p=preview&open=app%2Fapp.component.ts – Newcomer

+0

此評論來自評論頻道。我不是在尋求一個笨拙的人,而是問一些關於你的代碼如何工作的代碼解釋。詢問和未來的讀者知道你的代碼是如何工作是有幫助的。 –