Encountering an issue in app.module.ts with Angular 6 when trying to pass an array of injectables to providers resulting in the error message: "Property 'length' of undefined cannot be read"

Below is an array containing injectables connected to services:

import { YouTubeSearchService,
     YOUTUBE_API_KEY,
     YOUTUBE_API_URL } from './you-tube.service';

export const youTubeSearchInjectables: Array<any> = [
    { provide: YouTubeSearchService, useClass: YouTubeSearchService },
    { provide: YOUTUBE_API_KEY, useClass: YOUTUBE_API_KEY },
    { provide: YOUTUBE_API_URL, useClass: YOUTUBE_API_URL }
];

I am attempting to pass this array to providers in my app.module.ts:

/*other imports*/
import { youTubeSearchInjectables } from './search-result/you-tube-search.injectables';

@NgModule({
  declarations: [
    AppComponent,
    SimpleHttpComponent,
    SearchResultComponent,
    SearchBoxComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [youTubeSearchInjectables],
  bootstrap: [AppComponent]
})
export class AppModule { }

However, I encountered an error message stating "ERROR in Cannot read property 'length' of undefined". Just a single line error.

I suspect the issue might be related to Angular versions. The project uses version 5 while I am on version 6. Though according to Angular documentation, the book-way should work. This has left me puzzled. Perhaps there's something I'm overlooking.

I even tried manually adding each injectable to app.module but faced the same error.

Your assistance would be greatly appreciated.

EDIT: I also attempted using "providedIn: 'root'," as per ng6 update guidelines, but it did not resolve the issue.

Just for reference, here is the Injectable class:

/*imports*/

export const YOUTUBE_API_KEY = 'keykeykey';
export const YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/search';

@Injectable({
  providedIn: 'root',
})
export class YouTubeSearchService {
  constructor(
    private http: HttpClient,
    @Inject(YOUTUBE_API_KEY) private apiKey: string,
    @Inject(YOUTUBE_API_URL) private apiUrl: string
  ) { }

  search(query: string): Observable<SearchResult[]> {
    // logic
  }
}

Answer №1

There are a couple of issues with the code you posted. Firstly, it appears that you are nesting an array inside another array to define your providers. To fix this, you can either directly reference the variable youTubeSearchInjectables or use the spread operator to combine your exported providers into the module's providers array.

Secondly, after resolving the first issue, you should also make sure to replace useClass with useValue for the variables YOUTUBE_API_KEY and YOUTUBE_API_URL, as these are simple string values and not classes.

const youTubeSearchInjectables: Array<any> = [
  { provide: YouTubeSearchService, useClass: YouTubeSearchService },
  { provide: YOUTUBE_API_KEY, useValue: YOUTUBE_API_KEY },
  { provide: YOUTUBE_API_URL, useValue: YOUTUBE_API_URL }
];

@NgModule({
  providers: [
    ...youTubeSearchInjectables
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

What could be causing my object property to be undefined when used in an if statement?

My attempt to search through an array using a for loop is not yielding the expected results. let matrix = []; for(let i=0; i<this.row; i++){ for(let j=0; j<this.column; j++){ if(this.grid[i][j].name != ""){ ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as sh ...

Best practices for making API calls with axios in React

When accessing a backend API to retrieve a product in my frontend React application using async/await axios, I have defined a function like this: export const getProduct = ():Promise<Product> => { const {data} = await axios.get<Product>(&a ...

Encountering a SassError while trying to create unique themes with Angular Materials

I'm currently in the process of designing a unique theme for Angular Materials by following the instructions provided in this guide:https://material.angular.io/guide/theming#defining-a-custom-theme However, I've encountered an issue while attemp ...

Option to modify the arguments of a method in a parent class

I encountered an interesting problem recently. I have two classes: class Animal { public talk() { console.log('...'); } } and class Dog extends Animal { public talk(noise: string) { console.log(noise); super.talk() } } The i ...

Improved method for linking two enums with similar appearances

Currently, I use two enums as shown: enum Tab { Approved = "Approved", Pending = "Pending", Sold = "Sold", } enum ProductStatus { Approved = "Approved", Pending = "Pending", Sold = "Sold&q ...

Prettier mandates that single-line if-statements without curly braces must be written on the same line

Having recently delved into the EsLint documentation, I've adopted the curly rule set to warning for instances of multiple or nested rows of statements within conditionals. "rules": { "curly":["warn", "multi-or-nes ...

What is the method for installing TypeScript declarations for packages with scopes or namespaces using @types?

My current challenge involves the use of TypeScript and my desire to utilize a scoped package such as @foo/bar or @babel/core that does not include its own type declarations. My attempted solution so far has been to execute the following command: npm ins ...

Leveraging $sceDelegateProvider for allowing Youtube in Typescript

I'm currently facing an issue with my app where I am trying to enable users to input Youtube URLs for videos to be displayed on the site. However, before implementing this feature, I need to whitelist Youtube. How can I adjust my typescript file (app. ...

Passing parameters in Angular routes may result in routes not being able to match

I am facing an issue while trying to access a component that requires 2 URL parameters. Despite providing the parameters, I encounter an error indicating that the routes cannot be matched. const routes: Routes = [ { path: 'home', componen ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

Displaying images in Ionic from a JSON URL source

I am having trouble getting an image from a JSON to display on an Ionic card. Although I can see the JSON response in the console log, the image is not showing up on the card, leaving it blank. It seems like I'm making a mistake in the HTML code. Any ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

Learn how to send an SMS using Angular and Ionic 4 without having to open the native SMS app

I have been actively monitoring the GitHub repository for the Ionic Native SMS plugin at https://github.com/cordova-sms/cordova-sms-plugin. Following the suggested configuration from the repo, I have set it up as follows: var options = { repla ...

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

Using Angular 2, NodeJS, and Mongoose to send data from an Angular 2 frontend to a NodeJS backend REST API. However, encountering an issue where the Node API logs show that the OPTIONS

I am facing an issue with sending data from my Angular2 frontend API to the backend client, which is built using NodeJS and mongoose. When I inspect the data being sent on the Angular2 client through console.log, I can see that the correct values are being ...

What types should you use for an Axios response in React and TypeScript?

Trying to display a basic user list fetched from an API, which returns the following data: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] Struggling to understand how to deal ...