简体   繁体   中英

How to set a value on a filtered Observable

I am using Angular 9. I getting a filtered list of objects. I would like to alter the value on the returned object.

I have the following code:

  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;
  }

The following line:

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

Has this output:

在此处输入图像描述

I would like to set the x and y values to a hard-coded value (eg 1 ).

eg

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

Question

How can I set the above x and y values?

More info:

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;
  }

You just need to map your observable and then your array. Mapping an observable works almost the same way as with an array. Here you 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
));

Now you could subscribe to it or whatever you want to do with it, like so:

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

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM