【问题标题】:Clear an observable input in angular 8清除角度 8 中的可观察输入
【发布时间】:2020-11-03 08:16:32
【问题描述】:

我有这个动态搜索栏,当你输入一个字符串时,下面会出现一个与该字符串匹配的国家数组,为此我使用了新的主题,所以现在输入中的内容是一个可观察的。

一旦按下取消,我试图清除输入的值,但由于它是可观察的,我不能只清空字符串。

我尝试了以下代码,但控制台显示

无法读取未定义的属性“值”

模板:

<div>
    <h1>Country Search</h1>
    <div id="search-bar">
        <input #searchBox id="search-box" (input)="search(searchBox.value)" />
        <button (click)="delete(search-box.value)">Cancel</button>
        <ul class="search-result">
            <li *ngFor="let country of countries$ | async" >
              <a routerLink="/country-details/{{ country.name }}">{{ country.name }}</a>
            </li>
        </ul>
    </div>
</div>

打字稿

import { Component, OnInit } from '@angular/core';
import { Country } from '../../interfaces/country';
import { CountrySearchService } from '../../services/country-search.service';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.css']
})
export class SearchBarComponent implements OnInit {

  selectedcountry: Country;

  constructor(private countryService: CountrySearchService) { }
  
  countries$: Observable<Country[]>;
  private searchString = new Subject<string>();
  search(term: string): void {
    this.searchString.next(term);
  }

  delete(string: String) {  
    string = '';  
    console.log(string);
  }

  ngOnInit() {
    this.countries$ = this.searchString.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term: string) => this.countryService.searchCountries(term)),
    );
  }
}

【问题讨论】:

    标签: angular input observable


    【解决方案1】:

    你可以这样做(未经测试):

    export class SearchBarComponent implements OnInit {
    
      selectedcountry: Country;
    
      constructor(private countryService: CountrySearchService) { }
      
      countries$: Observable<Country[]>;
      private searchInput$ = new Subject<string>();
      private searchClear$ = new Subject<any>();
      search(term: string): void {
        this.searchInput$.next(term);
      }
    
      delete(string: String) {  
        this.searchClear$.next();
      }
    
      ngOnInit() {
          const search$ = merge(
              this.searchClear$.pipe(mapTo(')),
              this.searchInput$.pipe(
                  debounceTime(300)
              )
          );
        this.countries$ = search$.pipe(
          distinctUntilChanged(),
          switchMap((term: string) => this.countryService.searchCountries(term)),
        );
      }
    }
    

    merge 从任一 observable 中获取最新结果并将其折叠为一个。 mapTomap(() =&gt; '')基本相同。

    【讨论】:

      猜你喜欢
      • 2018-09-24
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多