触发valueChange with Initialized value – angular2

前端之家收集整理的这篇文章主要介绍了触发valueChange with Initialized value – angular2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在写一个angular2应用程序而且我遇到了什么.
首先,我有一个绑定到formControl的select:

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 of array.
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>

用户选择一个值时它会正常工作,它会触发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;
       });

但我有一个数组而不是一个Observable of Array!我错过了什么?
我怎样才能使它工作?

感谢您阅读本主题,对不起英语也不好意思!

可能的解决方案 :
1)使用startWith

this.profilesBy = this.myControl.valueChanges
      .startWith(DEFAULT)
      .map(text => new formatQuery(text.value))
      .switchMap(body => this.getGroupBy(body,res)=> res.json().aggregations.group_by_type.buckets);

解决方法

可能的解决方案是使用 startWith运算符:

this.profilesBy = this.myControl.valueChanges
  .startWith(DEFAULT_OPTION)
  .map(text => new formatQuery(text.value))
  .switchMap(body => ...);

猜你在找的Angularjs相关文章