请考虑以下场景,也可以在这里https://stackblitz.com/edit/ionic-4-observables-playground获得:
题
当我修改输入字段的值u1
和u3
变化。由于[(NgModel)]
纠缠不清u1
,我希望u1
并u3
在键入新值后立即在内存中对其进行修改,但只能进行瞬时读取,u1
而不能u3
。
我想念什么?
问题编辑1
我期望:[(ngModel)]="u1.username"
更改其值是因为双向数据绑定,但是u3
由于没有任何NgModel而不会<p>u3: {{u3.username}}</p>
情境
home.page.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]
});
}
}
user.service.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);
}
}
home.page.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>
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句