简体   繁体   中英

RxJS behavior subject and Angular ngModel binding with ngFor

Not sure how to ask this, so if anyone can clear it up please do. If I put an angular component on a page twice and get the data from a behavior subject, everything works fine, until I bind to an input using ngModel. It appears as though I don't understand what's happening. I have attached a plunker. When you update the input, it updates everywhere. I'm not sure I'm being clear, but the plunker hopefully makes it obvious.

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

app component:

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() { }
}

the component:

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;
  }
}

the service

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();
  }

}

为什么!

You should return different object references

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

subscribe to the service and use index for different objects

@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);

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM