首页 > 解决方案 > [(NgModel)] 是否更新行为主题?

问题描述

考虑以下场景,也可在此处获得https://stackblitz.com/edit/ionic-4-observables-playground

问题

当我修改输入字段时, 和 的值会u1发生u3变化。由于[(NgModel)]与 纠缠不清u1,因此我希望u1u3在输入新值后立即在内存中进行修改,但对于u1 not只能瞬时读取u3

我错过了什么?

问题编辑 1

我期望:[(ngModel)]="u1.username"因为双向数据绑定而改变它的值,但不是u3因为没有任何 NgModel<p>u3: {{u3.username}}</p>

设想

主页.ts

import { Component } from '@angular/core';
import {Observable, BehaviorSubject} from 'rxjs';
import 'rxjs/add/observable/from';
import {UserService} from '../user.service'

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {
  private u ='1'
  private all
  private u1 = {username: undefined}
  private u2 = {username: undefined}
  private u3 = {username: undefined}

  constructor(private users:UserService){}

  ngOnInit(){
    this.u3 = this.users.findByUsername(this.u)
    this.users.userList.subscribe( (data) => {
      this.all = data
      this.u1 = this.users.findByUsername(this.u);
      this.u2 = data[1]
    });
  }
}

用户服务.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable, BehaviorSubject} from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {

  public userList : BehaviorSubject<any[]> = new BehaviorSubject([
    { username: '1'}, {username: '2'}]);

  constructor() {}

  findByUsername(username: string) {
    return this.userList.value.find(each => each.username === username);
  }

}

主页.html

<ion-content padding>
  <ion-item>
    <ion-label position="floating">username</ion-label>
    <ion-input
    name="username"
    type="text"
      [(ngModel)]="u1.username"
      required
    ></ion-input>
  </ion-item>
  <p *ngFor="let each of all; let i = index">u{{i +1}}: {{each.username}}</p>
  <p>u3: {{u3.username}}</p>
</ion-content>

标签: angulartypescriptrxjs

解决方案


u1并且u3是对同一个对象的两个引用。所以如果你修改u1,你也会修改u3:它们是同一个对象:

this.u3 = this.users.findByUsername(this.u)
// so u3 is the element from the list which has this.u as its name

this.u1 = this.users.findByUsername(this.u);
// so u1 is also the element from the list which has this.u as its name

推荐阅读