一个组件中的数据不会与可注入的数组绑定

时间:2016-03-11 11:28:59

标签: data-binding angular

我有以下问题:

我有一个组件,我在调用它:

this.users = UsersInj.getUsersCollection()

UsersInj中,我有:

@Injectable()
export class UsersInj{
    public users:any = [];
    constructor(private _http:Http){
        this.getUsers().subscribe(
            success=>{
                this.users = success.json();
            },
            error =>{
                console.log('error')
            }
        )
    }

    getUsers(){
        return this._http.get('/api/user');
    }

    getUsersCollection(){
        console.log('GET USERS COLLECTION :',this.users);
        return this.users;
    }
}

但是,我的组件中的this.users.length始终为0.任何想法?

更新

当我在this.users中将UsersInj打包在对象中时,它会起作用。

PLNKR

1 个答案:

答案 0 :(得分:1)

在plunker中,您在创建TheContent时复制值(引用)。

export class TheContent {

  name: any;

  constructor(public nameService: NameService) {
    console.log("content started");
    this.info = nameService.info
    this.names = nameService.names;
  }
  changeMyName() {
    this.nameService.change();

  }
}

NameService中,您将新数组分配给this.names

this.names = success.json();
this.names中的{p> TheContentthis.names中的NameService现在已不再连接。

您可能想要做的是

  change(){
    this.info.name = "Jane";
    this.http.get('https://api.github.com/repos/vmg/redcarpet/issues?state=closed').subscribe(success=>{
      while(this.names.length > 0) {
        this.names.pop();
      }
      this.names.push.apply(this.names, success.json());
      console.log('names: ' + this.names);
    });
  }

或者将新数组再次复制到TheContent

在Angular中使用Observable允许感兴趣的各方订阅更改并通过通知传递新值是首选方式。另请参阅https://stackoverflow.com/a/35568924/217408