簡體   English   中英

Angular:搜索過濾器 rxjs

[英]Angular: search filter rxjs

我實現了一個函數,它按名稱在輸入按鈕中查找但是我有一個問題,我在那里做了一個條件,我希望輸入現在為空,所以它會變為假並顯示我的所有數據。

現在,只要 INPUT 為空,我就寫了一條消息“未找到”: 在此處輸入圖像描述

我想要的是,一旦輸入為空,它將向我顯示所有數據,如果它不為空,那么它將向我顯示適當的數據,或者如果它不存在,那么它將找不到: 在此處輸入圖像描述

我的界面:

export interface Post{
    id:number,
    date: Date,
    authorName:string,
    content:string;
}

我的種子日期:

  createDb() {
    const posts: Post[] = [
      {id:1,authorName:"Daniel",content:"Amazon’s Garage Delivery Service"
      ,date:new Date('11/12/20')
    },
      {id:2,authorName:"Omer",content:"Jake From State Farm "
      ,date:new Date('12/20/21')},
      {id:3,authorName:"Lior",content:"The General"
      ,date:new Date('02/01/22')},
      {id:4,authorName:"Tomer",content:"Spotify’s Wrapped "
      ,date:new Date('11/11/20')},
    ];
    return {posts};

html:

<input
  type="search"
  (input)="SearchPostsByName($event)"
  [(ngModel)]="authorName"
/>
<div *ngFor="let post of validPosts">
  <ng-container *ngIf="isExists">
    The name of the author is <b>{{ post?.authorName }}</b> with content
    <b>{{ post?.content }}</b> and released it on the date
    <b>{{ post?.date }}</b>
  </ng-container>
</div>
<br>

打字稿:

posts: Post[] = [];
   authorName = "";
   content = "";
   date = new Date();
   isExists = false;
   validPosts: Post[] = [];
   Search:string=''; 

  constructor(private postService: PostService) { }

  ngOnInit(): void {
    this.postService.getPosts().subscribe((posts)=> {
      this.posts = posts;
    });
  }
  
  SearchPostsByName($event : Event) {
    console.log($event);
    if (this.authorName) {
      this.validPosts = this.posts.filter((value) => value.authorName === this.authorName!); 
      if (this.validPosts.length > 0
      ) {
        console.log('found');
        this.isExists = true;
      } else {
        this.isExists = false;
      }
    }
  }

我的服務:

export class PostService {

  private postsUrl = 'api/posts';

  constructor(private http: HttpClient) { }

  getPosts(): Observable<Post[]> {
    return this.http.get<Post[]>(this.postsUrl);
  }

  addPost(post: Post): Observable<Post> {
    let httpOptions = {
      headers: new HttpHeaders({'Content-Type':'application/json'})
    };
    
    return this.http.post<Post>(this.postsUrl, post, httpOptions)
  }

我認為最大的錯誤是您忘記在ngOnInit validPosts這解釋了為什么您一開始沒有看到任何帖子:

  ngOnInit(): void {
    this.postService.getPosts().subscribe((posts) => {
      this.posts = posts;
      this.validPosts = posts;
    });
  }

如果您想在空搜索中顯示所有帖子,您可以檢查搜索關鍵字是否為空字符串,如果是,請將您的validPosts設置為posts

    const searchKey = ($event.target as HTMLInputElement).value;

    if (searchKey === '') {
      this.validPosts = this.posts;
      return;
    }

應該就是這樣!

如果您想進一步改進,我還有一些其他建議:

  1. 對於這樣的簡單搜索,您不需要使用雙向數據綁定,只需按搜索關鍵字過濾posts就可以了。
  2. 您不必創建isExists變量來跟蹤是否有任何validPosts ,因為它是一個數組,您可以檢查它的長度。
  3. 您可以創建一個模板來顯示空的帖子 html
  SearchPostsByName($event: Event) {
    const searchKey = ($event.target as HTMLInputElement).value;

    if (searchKey === '') {
      this.validPosts = this.posts;
      return;
    }

    this.validPosts = this.posts.filter(
      (value) => value.authorName === searchKey
    );
  }
<input type="search" (input)="SearchPostsByName($event)" />
<ng-container *ngIf="validPosts.length; else emptyPostTpl">
  <div *ngFor="let post of validPosts">
    The name of the author is <b>{{ post?.authorName }}</b> with content
    <b>{{ post?.content }}</b> and released it on the date
    <b>{{ post?.date }}</b>
  </div>
</ng-container>
<br />

<ng-template #emptyPostTpl>
  <span style="font-size: 1rem; font-weight: bold; display: block"
    >No post found</span
  >
</ng-template>

想要更進一步?

  1. 看看onPush更改檢測以提高性能。
  2. 學習 RXJS 並實現去抖動搜索!

我建議你用keyup替換你的輸入事件

 <input type="search" (keyup)="SearchPostsByName($event)" [(ngModel)]="authorName" />

在 SearchPostsByName($event) 中,查詢event$.target.value以檢查是否有任何輸入:

 SearchPostsByName($event : Event) { if(!$event.target.value.length) { return; } if (this.authorName) { this.validPosts = this.posts.filter((value) => value.authorName === this.authorName!); if (this.validPosts.length > 0 ) { console.log('found'); this.isExists = true; } else { this.isExists = false; } }

暫無
暫無

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

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