【问题标题】:Angular: Filter Service via API requestAngular:通过 API 请求过滤服务
【发布时间】:2021-05-02 07:15:47
【问题描述】:

我正在使用过滤器,并且需要读取该值才能发送带有 url 中值的 API 请求。 我使用this API。我能够过滤这两个类别。选择两个后,我们想在 url 中发送一个包含两个选定值的 API 请求。

我们生成了一个后端脚本来过滤,我需要做的就是发送一个带有修改后 url 的请求。

app.component.ts

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  lines: any[];
  filteredLines: any[];
  filterBy;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get("https://api.mocki.io/v1/26fce6b9").subscribe(lines => {
      this.lines = lines;
      this.filteredLines = [...this.lines];
    });
  }

  filter() {
    this.filteredLines = [
      ...this.lines.filter(dropdown => dropdown.name.includes(this.filterBy))
    ];
  }


    /** Here I need a script onClick button that reads the selected values and sending a get-request of API link above added with the filtered values: 

                 With click on the submit-button, I want to send the API request.
If api.com/data is the link, the request link would be like api.com/data?line=A&workCenter=1

The "?" is for category Line, and "&" for workCenter.
**/

 
  }
}

app.component.html

<select>
      <option>Line</option>
      <option *ngFor="let dropdown of filteredLines" (keyup)="filter()">
        {{dropdown.line}}
      </option>
</select>
<select>
      <option>Work Center</option>
      <option *ngFor="let dropdown of filteredLines" (keyup)="filter()">
        {{dropdown.workCenter}}
      </option>
</select>
  <form action="" method="post">
    <input type="submit" name="request" value="Submit" />
</form>

我创建了一个 Stackblitz project 以便更好地理解。

【问题讨论】:

    标签: javascript angular typescript api filter


    【解决方案1】:

    从您的示例中,您需要添加将绑定到所选值的 [(ngModel)]。 你可以在这里找到更多关于如何正确使用选择的信息More info

       <select [(ngModel)]="selectedLine">
      <option>Line</option>
      <option *ngFor="let dropdown of filteredLines" (keyup)="filter()">
        {{dropdown.line}}
      </option>
    </select>
    <select [(ngModel)]="selectedWorkCenter">
      <option>Work Center</option>
      <option *ngFor="let dropdown of filteredLines" (keyup)="filter()">
        {{dropdown.workCenter}}
      </option>
    </select>
    <form action="" method="post">
      <input type="submit" name="request" value="Submit" (click)="Submit()" />
    </form>
    

    然后在你的 ts 文件中,声明 select 变量和访问值,就像在点击函数 Submit 中一样。

    import { Component } from "@angular/core";
    import { HttpClient } from "@angular/common/http";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      lines: any[];
      filteredLines: any[];
      filterBy;
      selectedLine; // For first select
      selectedWorkCenter; // For second select
    
      constructor(private http: HttpClient) {}
    
      ngOnInit() {
        this.http.get("https://api.mocki.io/v1/26fce6b9").subscribe(lines => {
          this.lines = lines;
          this.filteredLines = [...this.lines];
        });
      }
    
      filter() {
        this.filteredLines = [
          ...this.lines.filter(dropdown => dropdown.name.includes(this.filterBy))
        ];
      }
    
      requestAnDieAPI() {
        console.log(this.filteredLines); // hier muss mein API post request hin
      }
    
      Submit() {
        var baseUrl = `https://api.mocki.io/`;
        var url = `${baseUrl}data?line=${this.selectedLine}&workCenter=${
          this.selectedWorkCenter
        }`;
        this.http.get(url).subscribe(response => {
          // response
        });
      }
    }
    

    【讨论】:

      【解决方案2】:

      我不清楚您是否想向 API 调用发送多个 { line, workCenter } 对象,但根据您设置 Stackblitz 项目的方式,我假设您只想发送一个。

      从未在&lt;option&gt; 元素上看到(keyup),而是在&lt;select&gt; 上使用[(ngModel)]

      <select [(ngModel)]="selected.line">
            <option [value]="null">Line</option>
            <option *ngFor="let dropdown of filteredLines" [value]="dropdown.line">
              {{dropdown.line}}
            </option>
      </select>
      <select [(ngModel)]="selected.workCenter">
            <option [value]="null">Work Center</option>
            <option *ngFor="let dropdown of filteredLines" [value]="dropdown.workCenter">
              {{dropdown.workCenter}}
            </option>
      </select>
      <!-- the use of the form in this case is not required       -->
      <!-- since you are using requestAnDieAPI to do the api call -->
      <form action="" method="post" (submit)="requestAnDieAPI()">
          <input type="submit" name="request" value="Submit" />
      </form>
      <!-- You can also use just a simple button -->
      <button (click)="requestAnDieAPI()">Submit</button>
      

      那么你的组件(模型)应该包含一个映射接口(视图)的selected变量

      import { Component } from "@angular/core";
      import { HttpClient } from "@angular/common/http";
      
      @Component({
        selector: "my-app",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.css"]
      })
      export class AppComponent {
        lines: any[];
        filteredLines: any[];
        filterBy;
        selected = {
          line: null,
          workCenter: null
        };
      
        constructor(private http: HttpClient) {}
      
        ngOnInit() {
          this.http.get("https://api.mocki.io/v1/26fce6b9").subscribe((lines: any[]) => {
            this.lines = lines;
            // this.filteredLines = [...this.lines];
            // better:
            this.filteredLines = this.lines.slice();
            // or either this.filter() directly
          });
        }
      
        filter() {
          // this.filteredLines = [
          //  ...this.lines.filter(dropdown => dropdown.name.includes(this.filterBy))
          // ];
          // this is redundant, better:
          this.filteredLines = this.lines.filter(dropdown => dropdown.name.includes(this.filterBy))
        }
      
        requestAnDieAPI() {
          if (this.selected.line != null && this.selected.workCenter != null) {
            let apiUrl = "https://api.com/data?line=" + this.selected.line + 
                           "&workCenter=" + this.selected.workCenter
            this.http.get(apiUrl).subscribe(/* Your optional response callback/subscriber here */);
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-25
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多