【问题标题】:RxJS behavior subject and Angular ngModel binding with ngForRxJS 行为主体和 Angular ngModel 与 ngFor 的绑定
【发布时间】:2023-03-27 13:20:01
【问题描述】:

不知道怎么问这个,所以如果有人可以解决这个问题,请做。 如果我将一个角度组件放在页面上两次并从行为主题中获取数据,那么一切正常,直到我使用 ngModel 绑定到输入。好像我不明白发生了什么。我附上了一个plunker。当您更新输入时,它会随处更新。我不确定我是否清楚,但希望 plunker 让它显而易见。

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

应用组件:

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

}

【问题讨论】:

  • 您期待不同的东西吗?它们都共享对同一个可变对象的引用。

标签: angular rxjs


【解决方案1】:

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

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

  }
}

【讨论】:

  • 如果 TodoComponent 被销毁会自动取消订阅吗?
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 2018-11-11
  • 2018-03-21
  • 2016-07-27
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多