Service function declaration results in the error message 'function is not a valid function.'

This particular service is designed to return an array of 1, 2, 3 for testing purposes.

import {Injectable} from '@angular/core';

    @Injectable()
    export class CitiesService {

        getCities() {
          return ['1', '2', '3'];
        }
    }

The AppComponent serves as an autocomplete box. It utilizes Formbuilder to access the input field and obtain the value entered by the user.

The primary objective behind using CitiesService is to extract a list of cities from a JSON file.

import { Component, Inject } from '@angular/core';
import { Observable } from 'rxjs/RX';
import { FormBuilder, FormGroup, FormsModule } from '@angular/forms';
import { CitiesService } from './cities.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CitiesService]
})
export class AppComponent {
  form: FormGroup;
  searchTerm: string;

  constructor(@Inject(FormBuilder) private _CitiesService: CitiesService, private _fb: FormBuilder){
    var a = this._CitiesService.getCities();
    this.form = _fb.group({
      search: []
    });
    var search = this.form.controls['search'];
    search.valueChanges
          .subscribe(data => this.searchTerm = data);
  }

}

However, I am encountering the following error:

EXCEPTION: this._CitiesService.getCities is not a function

Answer №1

Attempting to use your _CitiesService as a FormBuilder might not be what you intended.

 constructor(@Inject(FormBuilder) private _CitiesService: CitiesService, private _fb: FormBuilder){

This line indicates that the first parameter in your constructor should be injected using the provider for FormBuilder (@Inject(FormBuilder)). It is unlikely that this is your desired behavior.

To correct this issue, remove the @Inject(FormBuilder). This annotation is unnecessary unless the type of your constructor parameter does not match the provider's type. Additionally, if you do want to use it, remember to place @Inject in front of the relevant parameter.

To rectify the situation, update your line to:

constructor(private _CitiesService: CitiesService, @Inject(FormBuilder) private _fb: FormBuilder){

Alternatively,

constructor(private _CitiesService: CitiesService, private _fb: FormBuilder){

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

Is there a possibility in TypeScript to indicate "as well as any additional ones"?

When working with typescript, it's important to define the variable type. Consider this example: userData: {id: number, name: string}; But what if you want to allow other keys with any types that won't be validated? Is there a way to achieve thi ...

Ways to allocate a random color within an array?

Hi there, I'm trying to create chips with random colors from an array in my code. I attempted to use a color string array and assign them to the chips one after the other, but it didn't work as expected. Any suggestions on how I can achieve this? ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

I am facing issues with my filtering functionality on the Angular Typescript mat-table component

I am facing issues while trying to filter my table, the reaction is not correct and I can't seem to find where I went wrong. Here is the HTML part : <mat-form-field appearance="outline"> <mat-label>Search</mat-label> & ...

Identifying the category of a value through a conditional check on another value

I am looking for my code editor to automatically determine the type of extraData based on the value of error, which is being narrowed down by an if statement: export enum ErrorCodes { Unknown = 'UNKWN', BadRequest = 'BDREQ', } int ...

Error in Angular compiler-cli: The namespace 'ts' does not contain the exported member 'ResolutionMode'

Currently working on a web application using Angular 16 in Webstorm. The application is still in the pre-release stage, with only minimal functionality completed so far. While editing with ng serve running to test changes as they were made, encountered an ...

Error: Code layer not located while utilizing "sam invoke local" in AWS

Currently, I am engaged in an AWS project where I am developing two lambda functions. Both of these functions rely on a common codebase stored in the node_modules directory, which is placed in a separate layer named AWS::Lambda::LayerVersion, not to be con ...

Utilizing union type return values in Typescript

Looking to incorporate shelljs (via DefinitelyTyped) into my Typescript 1.5-beta project. I want to utilize the exec function with the specified signature: export function exec(command: string, options: ExecOptions): ExecOutputReturnValue | child.ChildPro ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

When incorporating a second overload as an object, it is generating a pair of errors

I'm currently working on creating an overload function that takes either two arguments or one argument as an object, which will be used in the following way: // Two parameters obj.set('a', '123'); obj.set('b', 'efg&a ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

Accessing Parent Component's Route Parameters in Child Component in Angular 5

Here we have the add-new-folder.component, which functions as a child component of the folder.component. When routing to the add-new-folder.component from the parent folder.component, I need to access the userid parameter of the parent component in its chi ...

What sets apart the various download options for Typescript, such as npm, NuGet, and Marketplace?

While working in VS Pro, I am a beginner developer in TypeScript (as well as React and Node...). I am focused on truly understanding how these technologies integrate and function together, rather than simply copying commands and code snippets into files. ...

How can one efficiently update post statuses in Ionic 4 without having to constantly reload or refresh the webpage?

I have created a dynamic list of posts, each with a "like" and a "comment" button. The issue I'm facing is that whenever I click on the like button, I have to manually refresh the page for the changes to appear. One approach I considered was incorpor ...

Adjust the request timeout using Angular

Currently, I am utilizing rxjs and httpclient from Angular to execute a get request. Here is an example of the code: get<T>(path: string): Observable<T> { return this.http .get<T>(path, { headers: this.httpOptions.headers }) ...

Sending data from the LoginComponent to the RootComponent

I am facing a challenge with implementing *ngIf to hide the login/logout option in the navbar based on the user's authentication status. When logged in, I want to hide the logout link. Here is my current setup. app.component.ts import { Component, O ...

Instead of the type definition file, navigate to the TypeScript source file within VS Code

A unique npm library I developed is utilized in various main projects, with all the sources stored within a /src directory and written in TypeScript. The compiler options listed in the tsconfig.json file include "sourceMap": true and "outDir": "dist". Addi ...

Beware of the 'grid zero width' alert that may appear when utilizing ag-Grid's sizeColumnsToFit() function on multiple ag-Grids that are shown within a tab menu

Encountering a warning message when resizing ag-Grid and switching between tabs. The warning reads: ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen? A demo of this ...

A TypeScript function that converts a value into an array if it is not already an array, ensuring the correct type is output

I'm attempting to develop a function that wraps a value in an array if it is not already an array. export function asArray<T extends Array<any>>(value: T): T export function asArray<T>(value: T): T[] export function asArray(value: a ...