我正在编写一个 angular2 应用程序,但遇到了一些问题。
首先,我有一个绑定(bind)到 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);
}
}
所以,myControl
是 formControl
, 和 profilesBy
是数组的 Observable。
formatQuery
只需使用 select 和 getGroupBy
的值格式化查询的主体返回 http
请求(即:http.post(url, body) ...)。
然后我分配响应: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>
当用户选择一个值时它工作得很好,它会触发 valueChanges
并链接 Action !
所以我很高兴。我认为这是一种优雅的方式,而不是使用 ngOnChanges()
现在这里是我找不到使其工作的方法的地方。基本上,我想用一个值初始化选择并触发(无需任何用户操作)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;
});
但我得到了一个Array
而不是 Observable of Array
!我想念什么?
我怎样才能让它发挥作用?
使用 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);
最佳答案
可能的解决方案是使用 startWith运算符(operator):
this.profilesBy = this.myControl.valueChanges
.startWith(DEFAULT_OPTION)
.map(text => new formatQuery(text.value))
.switchMap(body => ...);
关于angular - 使用初始化值触发 valueChange - angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41161352/