gpt4 book ai didi

angular - RxJS 行为主题和 Angular ngModel 与 ngFor 绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 17:44:54 24 4
gpt4 key购买 nike

不知道怎么问这个问题,所以如果有人能解决这个问题,请解决。如果我将 Angular 组件放在页面上两次并从行为主体获取数据,一切正常,直到我使用 ngModel 绑定(bind)到输入。好像我不明白发生了什么。我附上了一个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();
}

}

Why!

最佳答案

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

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

}
}

关于angular - RxJS 行为主题和 Angular ngModel 与 ngFor 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41453768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com