簡體   English   中英

如何在過濾后的 Observable 上設置值

[英]How to set a value on a filtered Observable

我正在使用 Angular 9。我得到了一個過濾的對象列表。 我想更改返回的 object 上的值。

我有以下代碼:

  private setFilteredApproverOptions(): void {
    for (const field in this.approvalEditFormGroup.controls) {
      console.log(field);
      this.approvalEditFormGroup.get(field).valueChanges.subscribe(value => {
        if (value && typeof value.valueOf() === "string") {
          this.filteredApproverOptions = this._filter(value);
          this.filteredApproverOptions.forEach(person => {console.log(person)});
        }
      });
    }
  }

  private _filter(value: string): Observable<Person[]> {
    const filterValue: string = value.toLowerCase();
    let respApprovalState: Observable<Person[]> = this.getApproverOptions(filterValue);
    respApprovalState.subscribe(approverOptions => {
      return approverOptions.filter(option => (option.firstName.toLowerCase().includes(filterValue) || option.lastName.toLowerCase().includes(filterValue)));
    });
    return respApprovalState;
  }

  private getApproverOptions(searchString: string): Observable<Person[]> {
    let companyName: string = this.approvalEdit.companyName;
    let respApprovalState: Observable<Person[]> = this.service.getApprovers(companyName, searchString);

    respApprovalState.subscribe((approverOptions: Person[]) => {
      this.approverOptions = approverOptions as Person[];
      return approverOptions;
    },
    error => {
      console.log('Error calling getApprovers service', error);
      return null;
    });

    return respApprovalState;
  }

以下行:

this.filteredApproverOptions.forEach(person => {console.log(person)});

有這個 output:

在此處輸入圖像描述

我想將xy值設置為硬編碼值(例如1 )。

例如

x: 1, y: 1, personId: 105702...

問題

如何設置上述xy值?

更多信息:

export class Person {
    public constructor(init?: Partial<Person>) {
      Object.assign(this, init);
    }
    x: number;
    y: number;
    personId: number;
    firstName: string;
    lastName: string;
    email: string;
    companyName: string;
    staffCode: string;
  }

你只需要 map 你的 observable 然后你的數組。 映射 observable 的工作方式幾乎與使用數組相同。 這里是 go:

const mapped = this.filteredApproverOptions.pipe(map(    // obs.pipe(map(...)) is changing each value coming in an observable/subject
    pArr => pArr.map(p => ({...p, x: 1, y: 1}))          // arr.map(...) is changing each value in an array
));

現在你可以訂閱它或任何你想用它做的事情,像這樣:

mapped.subscribe(val => console.log(val));

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM