加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

触发valueChange with Initialized value – angular2

发布时间:2020-12-17 17:58:53 所属栏目:安全 来源:网络整理
导读:我正在写一个angular2应用程序而且我遇到了什么. 首先,我有一个绑定到formControl的select: export class MyComponent implements OnInit { profilesBy: Observableany[]; myControl = new FormControl(); constructor(public http: Http) { this.profilesB
我正在写一个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 => ...);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读