When a user inputs a city name in a text box, I need to check if it is valid by calling the onCityChange() function using ngModelChange. This function emits the user-entered data on an rxjs Subject, which I subscribe to in the ngOnInit() method. Utilizing the switchMap() operator, I query a weather search API via a service.
If the user enters a correct city name, the API is triggered with a 200 status. Subsequent entries also trigger the API appropriately. However, entering an incorrect city name results in a 404 status, but then correct entries fail to trigger the API. It seems that once a non-success status is received, the API stops firing for any subsequent city names. What could be causing this?
Provided below are the code snippets:
weather-search.component.html
<input type="text" name="city" placeholder="Enter City" [(ngModel)]="city" (ngModelChange)="onCityChange();">
City found: <b>{{data.name}}</b>
weather-search.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 = {};
})
}