如何按几个字段进行过滤,但不包括按通用属性向数组添加重复的匹配项

时间:2019-09-16 04:37:53

标签: angular rxjs filtering

有一个用户数组有一个过滤表单,其中的几个字段很少,并且需要两个字段如何确保早先在其他字段中重合的对象不会落入结果数组中?

输入每个字符时如何发出服务器请求,根据字母的最小匹配进行过滤。我在输入字段中按完整的短语进行了过滤

search.component

my $req = POST(
    $url,
    Authorization => 'Basic ' . encode_base64('admin' . ':' . 'Algosec123'),
    Content_Type => 'multipart/form-data',
    'Content' => { 'file_to_upload' => ["$location"] }
    );

  

它不是我真正需要的,但它仍然可以工作   这些代码从db获取数据

    searchUser() {//when we fileds already filled
                    this.users = [];//clear users array
     const user: User = {//create new user:User
      firstName: this.searchForm.controls.firstNameControl.value,
      lastName: this.searchForm.controls.lastNameControl.value,
      login: this.searchForm.controls.userNameControl.value,
      email: this.searchForm.controls.emailFormControl.value,
      phoneNumber: this.searchForm.controls.phoneFormControl.value
     };
     for (var key in user) {
      if (user[key] === "") {    //check epmty data
        delete user[key];    //delete unfilled properties
       }
     }

user.service.ts

 this.userservice.searchUser().subscribe(
                        users => {
                         users.forEach(item => {
                          for (var key in item) {
                           if ( String(item[key]).toLowerCase() === String(user[key]).toLowerCase()
                           ) {
                           if (this.users.includes(item)) {
                            continue;
                           } else {
                            this.users.push(item); //add to results arrays
                           }}}});
                        });
                        }

DB.json

  

我们通过byservice获得的数组

 export class UsersService extends BaseApi {
                     constructor(public http: HttpClient) {}
                     searchUser(): Observable<User[]> {
                      return this.get(`users`);//get users array from db*
                     }
                    }

建议通过rxjs做到这一点,因此,在subscription方法中,您只需声明结果,即可将所有逻辑转移到服务中

1 个答案:

答案 0 :(得分:0)

>make subscribe on each form control   
>key must calling like form control
>its subscrition initialize part
>create formgroup

    this.searchForm = new FormGroup({
      firstName: new FormControl("", [
        Validators.required,
        Validators.maxLength(20)
      ]),
      lastName: new FormControl("", [Validators.maxLength(20)]),
      login: new FormControl("", [Validators.maxLength(20)]),
      email: new FormControl("", [Validators.pattern(/^(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)]),
      phoneNumber: new FormControl("",Validators.maxLength(20),Validators.minLength(5),Validators.pattern(/^\d+$/)
      ])
    });

//conveyor subscribing need on afterViewInit,onInit,+ when after clearForm()

    Object.keys(this.searchForm.controls).forEach(key => {
       this.subscribeControls(this.searchForm.controls[key], key);
    });

//this an observable filtering

    subscribeControls(currentControl: AbstractControl, key: string) {
    currentControl.valueChanges
      .pipe(
        takeWhile(value => value !== null),
        filter(value => value.length > 2),
        debounceTime(500),
        switchMap(value =>
          this.userservice.searchUser().pipe(
            map(arrays =>
              arrays.filter(user => {
                return !(
                  user[key].toLowerCase().indexOf(value.toLowerCase()) !== -1
                )
                  ? false
                  : true;
              })
            )
          )
        )
      )
      .subscribe(arr => {
        ref: for (let index = 0; index < arr.length; index++) {
          const element = arr[index];
          const same = this.users.some(e => {
            return e.id === element.id;//user needs unique _id
          });
          if (same) {
            continue ref;
          }
          this.users.push(element);
        }
        console.log(this.users);//get matches!!!!!!!!!!!
      });
  }