Angular数组可观察对象未被更新。

huangapple go评论42阅读模式
英文:

angular array observable does not get updated

问题

HTML中的内容无需翻译,但是你提供的HTML代码中包含一些HTML实体编码,需要还原成正常的HTML标记。以下是已翻译和修复的HTML代码:

<small>{{(selectedLangs$ | async)}}</small>

请注意,HTML代码中的特殊字符已被还原,现在可以正确显示。如果数组的值发生更改,HTML中的小标签内容应该会相应更新。

英文:

I have ts code as below

selectedLangs : string[]  = []
selectedLangs$: Observable&lt;string[]&gt; = of(this.selectedLangs);

ngOnInit(){
    this.form.get( &#39;languages&#39; ).valueChanges
        .pipe(
            takeUntil( this._unSubscribeAll ),
            tap( langs =&gt; {
                this.selectedLangs = [];
                if( langs ) {
                    langs.forEach( ( lang: IOption ) =&gt; {
                        if( this.selectedLangs.find( f =&gt; f === lang ) === undefined ) {
                            this.selectedLangs.push( lang )
                        }
                    } )
                }
            } )
        )
        .subscribe();
} 

html

&lt;small&gt;{{(selectedLangs$ | async)}}&lt;/small&gt;

Should my html be updated if I am changing the value of the array?

答案1

得分: 1

这是您想要做的吗?

selectedLangs$: BehaviorSubject<string[]> = new BehaviorSubject([]);
    
ngOnInit() {
  this.form.get('languages').valueChanges.pipe(
    takeUntil(this._unSubscribeAll),
    tap((langs: IOption[]) => {
      const uniqueLangs = [...new Set(langs)];
      this.selectedLangs$.next(uniqueLangs);
    })
  ).subscribe();
}
英文:

Is this what you want to do?

selectedLangs$: BehaviorSubject&lt;string[]&gt; = new BehaviorSubject([]);

ngOnInit() {
  this.form.get(&#39;languages&#39;).valueChanges.pipe(
    takeUntil(this._unSubscribeAll),
    tap((langs: IOption[]) =&gt; {
      const uniqueLangs = [...new Set(langs)];
      this.selectedLangs$.next(uniqueLangs);
    })
  ).subscribe();
}

huangapple
  • 本文由 发表于 2023年2月23日 20:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定