【发布时间】: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