ByJ*_*yJC 4 valuechangelistener observable rxjs ngoninit angular
我正在写一个angular2应用程序而且我遇到了什么.首先,我有一个绑定到的选择formControl:
export class MyComponent implements OnInit {
profilesBy: Observable<any[]>;
myControl = new FormControl();
constructor(public http: Http) {
this.profilesBy = this.myControl.valueChanges
.map(text => new formatQuery(text.value))
.switchMap(body => this.getGroupBy(body, this.url), (_, res)=> res.json().aggregations.group_by_type.buckets);
}
}
Run Code Online (Sandbox Code Playgroud)
所以,myControl是formControl,并且profilesBy是一个Observable数组.
在formatQuery使用选择的值只格式化机构查询并getGroupBy返回一个http请求(即:http.post(URL,身体)...).
然后我分配了回复:res.json().aggregations.group_by_type.buckets
但是不要过多考虑这个问题.
这是我的模板:
<md-card>
<h4>Profiles group by :
<select [formControl]="myControl">
Some options ...
</select>
</h4>
<div *ngFor="let profile of profilesBy | async">
<strong>{{profile.key}} :</strong> {{profile.doc_count | number:'1.0-2'}}
</div>
</md-card>
Run Code Online (Sandbox Code Playgroud)
当用户选择一个值时它会正常工作,它会触发valueChange并链接动作!
所以我很高兴.我认为这是一种优雅的方式,而不是使用ngOnChanges()
现在,我无法找到使其有效的方法.基本上,我想用值初始化select并触发(没有任何用户操作)valueChange
我尝试使用[(ngModel)]:<select [formControl]="myControl" [(ngModel)]="selectedGroupBy">
但它没有触发它.
最后,我试着在方法中自己打电话 ngOnInit()
this.getGroupBy(new formatQuery(this.selectedGroupBy.value), this.url)
.subscribe((response) => {
this.profilesBy = response.json().aggregations.group_by_type.buckets;
});
Run Code Online (Sandbox Code Playgroud)
但我得到了一个Array而不是一个Observable of Array!我错过了什么?我怎样才能使它工作?
感谢您阅读本主题,对不起英语也不好意思!
可能的解决方案:1)使用startWith
this.profilesBy = this.myControl.valueChanges
.startWith(DEFAULT)
.map(text => new formatQuery(text.value))
.switchMap(body => this.getGroupBy(body, this.url), (_, res)=> res.json().aggregations.group_by_type.buckets);
Run Code Online (Sandbox Code Playgroud)
Ser*_*lov 10
可能的解决方案是使用startWith运算符:
this.profilesBy = this.myControl.valueChanges
.startWith(DEFAULT_OPTION)
.map(text => new formatQuery(text.value))
.switchMap(body => ...);
Run Code Online (Sandbox Code Playgroud)
要以编程方式更改 formControl 的值,您只需调用该setValue()方法:
Run Code Online (Sandbox Code Playgroud)setValue(value: any, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}?: { onlySelf?: boolean, emitEvent?: boolean, emitModelToViewChange?: boolean, emitViewToModelChange?: boolean }) : void将表单控件的值设置为 value。
所以对于你的情况:this.myControl.setValue(foo)应该触发valueChanges.
| 归档时间: |
|
| 查看次数: |
5350 次 |
| 最近记录: |