如何在 angular 中使用 get api 按名字和姓氏搜索?

How to search by first name and last name using get api in angular?

我想使用 get api 按名字和姓氏进行搜索。我已经实现了它并且它可以工作,但是当至少一个输入值正确而不是全部正确时它也可以工作。我希望它仅在输入的名字和姓氏都正确时才显示 table 行。我该怎么做?

export class SearchDeleteComponent implements OnInit {

  users:any;

constructor(private service: NewUserService, private route:ActivatedRoute, private router:Router) { }

  ngOnInit() {
    let resp=this.service.getUsers();
    resp.subscribe((data)=>this.users=data);
  }
public findUserByName(){
   

   let resp=this.service.getUserByFirstName(this.firstName);
    resp.subscribe((data)=>this.users=data);

    let lName=this.service.getUserByLastName(this.lastName);
    lName.subscribe((data)=>this.users=data);

 <form>
             
        
               <div id="custom-search-input">
                <div class="input-group col-md-12" style="text-align: center">
                                        
                    <input class="search-query" type="text"  placeholder="Search With first name" size="50"  name="name"  [(ngModel)]="firstName"/>
    
                </div>
             
                                <br>
                                <div class="input-group col-md-12" style="text-align: center">
                                    
                                    <input class="search-query" type="text"  placeholder="Search With last name" size="50"  name="name"  [(ngModel)]="lastName"/>
                    
                                </div>
</div>
</div>
</forms>

我个人的意见是,您添加另一个接受参数和 returns 您的预期输出的端点。这应该是首选解决方案。

如果你真的想坚持你的单一请求,我建议使用 forkJoin 和 lodashs intersection

const response = forkJoin([
  this.service.getUserByFirstName(this.firstName),
  this.service.getUserByLastName(this.lastName)
]);

response.subscribe(
  ([firstNameUsers, lastNameUsers]) => this.users = lodash.intersectionWith(firstNameUsers, lastNameUsers, lodash.isEqual)
);

或者你只执行一个请求并用第二个参数过滤响应

const response = this.service.getUserByFirstName(this.firstName).pipe(
  map(users => users.filter(user => user.lastName === this.lastName)),
);
response.subscribe(data => this.users = data);