RxJS行为主题和Angular ngModel绑定与ngFor

时间:2017-01-03 23:09:46

标签: angular rxjs

不知道怎么问这个问题,所以如果有人能清除它,请做。 如果我在页面上放置一个角度组件两次并从行为主题获取数据,一切正常,直到我使用ngModel绑定到输入。看起来好像我不明白发生了什么。我附上了一个龙头。更新输入时,它会随处更新。我不确定我是不是很清楚,但是有吸引力的希望能让它显而易见。

http://plnkr.co/edit/OQFEGVJAJF5kHhWoTOpm?p=preview

app组件:

import { Component } from '@angular/core';
import { FormsModule, FormBuilder, Validators } from '@angular/common';

import { TodoComponent } from 'app/todo.component';
import { TodoService } from 'app/todo.service';

@Component({
  selector: 'todo-app',
  template: `

    <h3>Component 1</h3>
    <todo-component></todo-component>

    <br /><br />

    <h3>Component 2</h3>
    <todo-component></todo-component>
  `
})
export class AppComponent {
  constructor() { }
}

组件:

import { Component } from '@angular/core';
import { TodoService } from 'app/todo.service';

@Component({
  selector: 'todo-component',
  template: `
    <div *ngFor="let t of test | async">
      <div>test: {{t.prop}}</div>
      <div>test: <input [(ngModel)]="t.prop"></div>
    </div>
  `
})
export class TodoComponent {
  private test: any;

  constructor(private todoService: TodoService) { }

  ngOnInit() {
    this.test = this.todoService.test;
  }
}

服务

import { Injectable } from '@angular/core';    
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class TodoService {
  private initialTestState = [{prop: 'val'}];
  private test$: BehaviorSubject<[]>;
  private test: Observable<[]>;

  constructor() {
    this.test$ = new BehaviorSubject<[]>(this.initialTestState);
  }

  get test() {
    return this.test$.asObservable();
  }

}

Why!

1 个答案:

答案 0 :(得分:0)

您应该返回不同的对象引用

  get test() {
    let obj = [{prop: 'val'}];
    return new BehaviorSubject<[]>(obj);
  }

订阅该服务并将index用于不同的对象

@Component({
  selector: 'todo-component',
  template: `
    <div *ngFor="let t of test; let i = index; ">
      <div>test: {{test[i].prop}}</div>
      <div>test: <input [(ngModel)]="test[i].prop"></div>
    </div>
  `
})

export class TodoComponent {
  private test: any;

  constructor(private todoService: TodoService) { }

  ngOnInit() {
    this.todoService.test.subscribe(o => this.test = o);

  }
}