Angular 2 [(ngModel)]不工作

时间:2017-04-23 18:57:08

标签: angular angular2-services angular2-components

NET Core和Angular 2应用程序。我已成功与Web API控制器通信,并可以在控制台中记录该对象。

但是,当我尝试在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>

2 个答案:

答案 0 :(得分:1)

[(ngModel)]="value"

中删除 li
 <li >
   <span>{{value.id}} {{value.userName}}</span>
 </li>

答案 1 :(得分: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>