【问题标题】:Angular 5 : API not calling after bad request on ngModelChangeAngular 5:对 ngModelChange 的错误请求后 API 未调用
【发布时间】:2018-10-23 21:06:48
【问题描述】:

我必须显示用户在文本框中输入的城市是否可用。对于文本框的 ngModelChange,我调用了一个函数 onCityChange()。在该函数中,我在 rxjs 主题上发出用户输入的数据。我已经在 ngOnInit() 方法中订阅了该主题。我还有 rxjs switchMap() 运算符,我在其中通过服务调用天气搜索 API(我还将在其中获取城市名称)。

现在,当我输入正确的城市名称时,API 会以 HTTP 200 状态的城市名称触发。之后,我还可以输入另一个城市名称,并使用该城市名称触发 API。当输入错误的城市名称时,API 会按预期以 HTTP 404 状态触发。但在那之后,当我输入正确的城市名称时,不会触发任何 API。也就是说,一旦 API 以非成功状态触发,它就不会在重新输入任何城市名称的情况下再次触发。有什么问题?

这里是sn-ps的代码

天气搜索.component.html

<input type="text" name="city" placeholder="Enter City" [(ngModel)]="city" (ngModelChange)="onCityChange();">
City found: <b>{{data.name}}</b>

天气搜索.component.ts

    private city: string = '';
    private data: any = {};
    private searchStream = new Subject<string>();

    constructor(private weatherService: WeatherService) { }

    onCityChange(){
        if(this.city)
          this.searchStream.next(this.city);
        else
          this.data = {};
      }

    ngOnInit() {
         this.searchStream
        .debounceTime(500)
        .distinctUntilChanged()
        .switchMap((input: string) => this.weatherService.searchWeatherData(input))
        .subscribe(
          (data) => this.data = data,
          (err) => {
            console.error(err);
            this.data = {};
          })
      }

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    你可以使用ObservablefromEvent静态方法如下:

    @ViewChild('city') city: ElementRef;
    
    
    
     ngOnInit() {
                 Observable.fromEvent(this.city.nativeElement, 'input')
                .debounceTime(500)
                .distinctUntilChanged()
                .switchMap((input: string) => this.weatherService.searchWeatherData(input))
                .subscribe(
                  (data) => this.data = data,
                  (err) => {
                    console.error(err);
                    this.data = {};
                  })
              }
    

    【讨论】:

      【解决方案2】:

      这是正确的行为。当订阅者收到错误通知时,它会取消订阅并因此处置链,这正是您的情况所发生的情况。

      您知道this.weatherService.searchWeatherData(input) 可能以错误结束,因此您可以捕获它并用您想要的任何内容替换它,而不是进一步传递它。看起来一个空的响应就足够了:

      ...
      .switchMap((input: string) => this.weatherService.searchWeatherData(input)
        .catch(error => Observable.empty())
      )
      ...
      

      这将捕获每个错误通知,并在合并到链中之前将其替换为Observable.empty()

      【讨论】:

        猜你喜欢
        • 2017-04-02
        • 2021-01-26
        • 1970-01-01
        • 1970-01-01
        • 2019-11-14
        • 1970-01-01
        • 2015-06-17
        • 2017-01-24
        • 2019-09-08
        相关资源
        最近更新 更多