Angular 5: ngModelChange not triggering API call on bad request

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 = {};
        })
}

Answer №1

It is considered correct behavior that when a subscriber receives an error notification, it unsubscribes and disposes of the chain. This aligns with the situation you are facing.

It is important to acknowledge that

this.weatherService.searchWeatherData(input)
may result in an error. Instead of simply passing it along, you have the option to catch the error and substitute it with an empty response:

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

This approach will intercept each error notification and exchange it with Observable.empty() before integrating it into the chain.

Answer №2

To implement this functionality, utilize the fromEvent static method within the context of the Observable class in the following manner:

@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 = {};
              })
          }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating conditional statements in Angular 2 templates - the power of if, elseif

Can the if elseif else structure be used in an Angular 2 template? Here is an example of using if else: [text]="company ? company.name : 'Select a company'" I am looking to incorporate elseif into this. ...

What's the process for validating i18n dictionaries using TypeScript?

Is there a way to enforce type checking on existing keys within dictionaries in react-i18next? This means that TypeScript will provide warnings at compile time if a key does not exist. For example: Let's say we have the following dictionary: { "f ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

Incorporate dynamic HTML snippets into the DOM with Angular 4

Looking to populate an unordered list element <ul> with small, straightforward snippets from my JavaScript. Just basic lines like <li>Label: Text</li>. Using the ViewContainerRef.createComponent(ItemComponent) method to create a new comp ...

Whenever I connect to an array, it appears that the changes are not accurately being displayed in the ngif directive within the markup

So I have this @Input in the parent component where I assign a value to it. Initially, it's an empty array but then I change it to an array with one item. The issue arises when I try to reflect this changed array in the form of an NGIF within the com ...

Issue: The TypeError reported is due to the absence of any definition for "_co.category.category_type"

I have two models: CategoryTypes and Categories. Each category type contains multiple categories. These are my two models. Categories Model import { Categories } from '../../categories/Mode/Categories' export class CategoryType { _id: strin ...

Prisma - Modify a single resource with additional criteria

Is it feasible to update a resource under multiple conditions? Consider the tables below: +----------+----------+ | Table1 | Table2 | +----------+----------+ | id | id | | param1T1 | param1T2 | | param2T1 | param2T2 | | idTable2 | ...

Inaccurate inference of pipe and compose function types within TypeScript

I have created functions called pipe and compose which can combine two functions into a new one, with the only difference being the order in which they are called when applied to an argument. Although both functions are generic, I am having trouble ensuri ...

Displaying ASP.Net Core Application on local IIS - Unable to locate content

I started a new project in Visual Studio Code by running the following command: dotnet new angular --use-local-db Afterwards, I upgraded Angular from version 8 to 10 and completed the project. To test it, I used dotnet watch run Everything was running ...

Ensuring that an object containing optional values meets the condition of having at least one property using Zod validation

When using the Zod library in TypeScript to validate an object with optional properties, it is essential for me to ensure that the object contains at least one property. My goal is to validate the object's structure and confirm that it adheres to a sp ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...

Error: The property '...' is not found in the ReactElement<any, any> type, but it is required in the type '{...}'

As a beginner in TypeScript, I am currently working on rendering a page by fetching data from getStaticProps. The code snippet I am using for this purpose is: import React, {FormEvent, useState} from "react"; import { InferGetStaticPropsType } fr ...

Angular: Issue with canActivate not functioning properly when using redirected routes

My application's router file is set up with the following routes: export const router: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', canActivate: [AuthGuar ...

Issue encountered while importing TypeScript files from an external module in a Next.js project

Encountering an issue within my Next.js project with the following project structure: ├── modules/ │ └── auth/ │ ├── index.ts │ ├── page.tsx │ └── package.json └── nextjs-project/ ├─ ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Angular 10 does not fulfill promises as expected

In the Angular 10 project I'm working on, I encountered an issue while trying to call an API request asynchronously using promises. The code I wrote didn't seem to execute the API call as expected and kept exiting at the first line without progre ...

What is the correct way to utilize a variable as a parameter in React Query while employing the axios.request(options) method?

I'm currently working on a React Query component with the following structure: function test () { const [var, setVar] = useState("") const options = { method: "GET", url: "https://api.themoviedb.org/3/search/tv" ...