Angular searchbar issue: Unable to assign parameter of type 'unknown' to parameter of type 'string'

I've been working on an Angular app to fetch data from an API successfully. However, I'm currently facing a challenge while implementing a search function in my component.ts file.

Here is the entire service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, take } from 'rxjs';
import { RouterModule } from '@angular/router';

@Injectable({
  providedIn: 'root'
})

export class MoviesService {

  baseUrl: string;
  apiKey: string;
  language: string;
  region: string;

  constructor(
    private http: HttpClient
  ) { 
    this.baseUrl = 'https://api.themoviedb.org/3/';
    this.apiKey = 'dd4d819639705d332d531217b4f7c6b6';
    this.language = 'en-US';
    this.region = 'US';

  }
  
  getCatalog() {
    return this.http.get(`${this.baseUrl}movie/top_rated?api_key=${this.apiKey}&page=1&language=${this.language}&region=${this.region}`) as Observable<Catalog>;

 }

 getMovie(id:string) {
  return this.http.get(`${this.baseUrl}movie/${id}?api_key=${this.apiKey}&language=${this.language}&region=${this.region}`) as Observable<Movie>;

}

getSearchedMovie(username:string): Observable<any> {
  return this.http.get(`${this.baseUrl}search/movie?api_key=${this.apiKey}&language=${this.language}&region=${this.region}`) as Observable<Movie>;

}}

export interface Catalog {
  page: number;
  results: Movie[];
  total_pages: number;
  total_results: number;
}
export interface Movie {
  title: string;
  id: number;
  overview: string;
  original_title: string;
  poster_path: string;
}

Now, moving on to the component.ts file:

import { NgFor } from '@angular/common';
import { Component, NgModule, OnInit } from '@angular/core';
import { debounceTime, distinctUntilChanged, switchMap, take } from 'rxjs';
import { Catalog, Movie, MoviesService } from 'src/app/services/movies.service';
import { RouterModule } from '@angular/router';
import { FormControl, FormGroup } from '@angular/forms';
import { CommonModule } from '@angular/common';


@Component({
  selector: 'app-catalog',
  templateUrl: './catalog.component.html',
  styleUrls: ['./catalog.component.css']
})
export class CatalogComponent {

  searchForm:FormGroup = new FormGroup({
    search: new FormControl('')

  })


  catalog: Movie[];
  constructor(
    private moviesService: MoviesService,
    public movieList:Array<any>=[],
  ) { 
  
    
    this.searchForm.get('search')?.valueChanges.pipe(debounceTime(1000)),
    switchMap((v) => this.moviesService.getMovie(v)).subscribe((v) => {
      this.movieList=v?.users
    })

  }

  ngOnInit() {
    this.moviesService.getCatalog().pipe(take(1)).subscribe(res =>{
      this.catalog = res.results;
      console.log("this catalog dentro del observable", this.catalog);
    });
  }
};

A particular line in the code seems to be causing issues:

this.searchForm.get('search')?.valueChanges.pipe(debounceTime(1000)),
    switchMap((v) => this.moviesService.getMovie(v)).subscribe((v) => {
      this.movieList=v?.users
    })

The errors are related to the second parameter (v) and .subscribe method:

  1. Argument of type 'unknown' is not assignable to parameter of type 'string'.
  2. Property 'subscribe' does not exist on type 'OperatorFunction<unknown, Movie>'.

Could you spot anything that might be missing or causing these errors?

Answer №1

To properly utilize the SwitchMap operator, it should be included in the pipe stack hierarchy.

this.searchForm.get('searchField')?.valueChanges.pipe(
      debounceTime(800),
      switchMap(value =>  this.moviesService.retrieveMovieInfo(value)
    )).subscribe(result => {
      this.movieList=result?.listOfMovies
    })

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

Trigger a new Action upon successful completion of another action

I am a newcomer to the world of Angular and Redux. I have a common question for which I can't seem to find the right answer or maybe just need a helpful tip. I am utilizing ngrx in my application and I need to update some basic user data and then refr ...

Ionic 2 hides the form input area within its input component

I set up a login page, but the input fields are not showing up on the form. Here is my current code: <ion-list> <ion-item> <ion-label fixed>Username</ion-label> <ion-i ...

Display the HTML string as regular text in an Angular application

I'm working on a blog project with Angular. I need to display HTML content retrieved from the database as plain text for each blog post preview. The HTML formatting was done with ngx-quill. While I can render the rich text using <quill-view [conte ...

When attempting to run npm install -g @angular/cli, there are no valid versions found for the undefined package

Currently operating on Windows 10 Enterprise. I am attempting to install Angular CLI for running an Angular project. I have input the following command. --> npm install -g @angular/cli Unfortunately, I encountered the following error. --> npm E ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

What benefits does a bundler offer when releasing packages on npm?

After working with Node.js for many years, I recently ventured into publishing my first Node.JS package for a wider audience. Feeling lost at the beginning, I turned to Google for guidance on how to do this specifically for typescript and stumbled upon thi ...

An issue occurred when retrieving the input value during a (change) event within a nested *ngFor loop in Angular

Within my table, I have implemented a nested loop using the *ngFor directive: <tbody> <tr *ngFor="let dept of salesTarget; let i = index"> <td>{{dept.dept}}</td> <td *ngFor="let month of monthList; ...

The Angular application continues to display the outdated component HTML template in the browser even after it has been updated

In my role, I am currently focusing on developing Angular libraries that can be reused across various projects within our software department. One of these libraries includes a login form that I have successfully published to npm and integrated into anothe ...

Merge different JSON files to generate a new JSON file

I am faced with a challenge involving 2 separate JSON files. Here is the content of each: User.json: { "users": [ { "username": "User1", "app": "Git", "role": "Manager" }, ...

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...

Implementing a boolean value in PrimeNG's p-dropdown version 7.x

I need a p-dropdown with two options to be selected based on the boolean value of the control. The control (NOTIF_ALL) is assigned a boolean value oldPendingTasksOptions=[ {"oldPendingTaskId": false, "oldPendingTasksName": "Not a ...

Tips for bringing in a text file within a NodeJS application using TypeScript and ts-node during development

I am currently developing a NodeJS/Express application using TypeScript, Nodemon, and ts-node. Within this project, there is a .txt file that contains lengthy text. My goal is to read the contents of this file and simply log it to the console in developmen ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Error: Cookie cannot be set due to headers already being sent

Here lies my code snippet import { Request, Response } from "express"; import { database } from "firebase-admin"; async function updateAccessToken( req: Request, res: Response, db: database.Database ) { try { await db ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Angular2 app hosted on firebase displaying an empty page

After developing an angular2 app, I followed the procedure for Firebase hosting. However, when I try to access my app, it is showing a default page instead. I would appreciate any help or guidance on this issue. https://i.sstatic.net/59aq7.png ...

Navigating to the HomePage using the nebular auth/login library with the login() function: A step-by-step guide

After setting up my Angular Project and installing the nebular library, I am working on creating 3 pages: Login, Register, and Home. I have successfully created the login and register pages using NbLoginComponent and NbRegisterComponent. Now, my goal is to ...

Generating a new object from a TypeScript class using JavaScript

Currently, I am facing an issue while attempting to call a JavaScript class from TypeScript as the compiler (VS) seems to be having some trouble. The particular class in question is InfoBox, but unfortunately, I have not been able to locate a TypeScript d ...

Showing elapsed time similar to YouTube in an Angular 8 application

Currently, I am developing an Angular application to replicate certain features found on YouTube by utilizing data fetched from an API. This API provides video timestamps in a string format Each timestamp follows this structure : YYYY-MM-DDTHH:MM:SS For ...

Issue with res.redirect not properly redirecting to https site

After reading numerous posts with the same title, I have tried several suggestions but none of them have worked. In my Angular2 app with a server API, I am looking to automatically redirect in production if it's not secure. The code below is the fir ...