How to Pass Data as an Empty Array in Angular 6

After successfully implementing a search function that filters names from an array based on user input, I encountered an issue when trying to make the searchData dynamic by fetching it from a Firebase database:

getArray(): void {
    this.afDatabase.list('/imones')
      .valueChanges()
      .subscribe(res => {
        console.log(res)//should give you the array of percentage.
        this.array = res;
      })
}

this.searchData = this.back.getArray();
  constructor(private completerService: CompleterService, private router: Router, public back: BackService,
             ) {
    this.dataService = completerService.local(this.searchData, 'name', 'name');
}

This resulted in an error being thrown:

https://i.sstatic.net/LnS5P.png

I am seeking guidance on how to resolve this issue. Any help is appreciated.

Answer №1

The issue lies in the constructor where this.SearchData is not recognized as an array. The solution is simple: 1. Ensure your service returns an observable instead of subscribing within the service itself. 2. Move your code from the constructor to ngInit for better initialization. 3. Access the value of searchData within the subscribe function.

It may be challenging to decipher your code, but if your service returns Observables rather than data, your component can be structured as follows:

constructor(private completerService: CompleterService, private router: Router, public back: BackService) {}
ngOnInit() {
  this.back.getArray().subscribe(res => {
    this.searchData = res;
    completerService.local(this.searchData, 'name', 'name').subscribe(res => {
      this.dataService = res;
    });
  })
}

// Alternatively, use switchMap for a cleaner approach
ngOnInit() {
  this.back.getArray().pipe(switchMap(res => {
    this.searchData = res;
    return completerService.local(this.searchData, 'name', 'name');
  })).subscribe(res => {
    this.dataService = res;
  });
}

Answer №2

When utilizing the getArray() method, it does not directly return an array. However, when subscribing to afDatabase.list, you can obtain an array of values. It is important to assign the value to your array within the subscribe callback.

getArray(): void {
this.afDatabase.list('/imones')
  .valueChanges()
  .subscribe(res => {
    console.log(res)//should give you the array of percentage.
    this.searchData = res;
  })}

If values are being received one at a time, you can use the following approach:

getArray(): void {
    this.afDatabase.list('/imones')
      .valueChanges()
      .subscribe(res => {
        console.log(res)//should give you the array of percentage.
        this.searchData.push(res); //searchData must be initialized as empty array
      })
}

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

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

Struggling to compile your Angular 2 application in Visual Studio 2015?

After carefully following all the steps outlined in the VISUAL STUDIO 2015 QUICKSTART documentation, I have also gone ahead and installed the "Microsoft .NET Core 1.0.1 VS 2015 Tooling Preview 2", even though it was not specifically mentioned in the docume ...

What is the best way to incorporate the async pipe into my codebase when working with GraphQL queries?

I am currently working on an Angular project where I utilize GraphQL to fetch data in my component. In the HTML code, I display an image of the result. However, I encountered an error in the console that said: ERROR TypeError: Cannot read property 'im ...

Angular Checkbox Click EventLearn how to handle click events on

How can I toggle the visibility of a form using ngIf when a click event is triggered by a checkbox? Below is the code for my column header and column values: <th><label class="btn btn-filter"> <input type="checkbox" ...

What is the syntax for typing the router instance in Next.js?

I'm working on a password reset request form in my Next.js project. Here's the code I have: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } fro ...

Troubleshooting Angular Prerendering: How Conditional JavaScript Usage Can Lead to 'document is not defined' Error

Currently, I am utilizing Angular 15 in an attempt to pre-render a website for SEO optimization. It has come to my understanding that certain elements such as document and window are unavailable during pre-rendering since the code does not operate within a ...

Comparing Angular's 'ng serve' and 'npm start' commands

Just a quick query regarding angular-cli. I'm curious, is it correct that when I use ng serve, I am utilizing the global installation of angular-cli but when I opt for npm start, I am using the local one? ...

Facing Syntax Errors When Running Ng Serve with Ngrx

Currently, I am enrolled in an Angular course to gain proficiency in ngrx. In a couple of months, I will be responsible for teaching it, so I am refreshing my memory on the concept. Strangely, even after installing it and ensuring my code is error-free, er ...

Encountering a problem with ng serve while attempting to launch the project

I am completely new to Angular and recently installed the latest version of Node.js along with Angular CLI globally. I cloned a project from GitHub and attempted to run it using 'ng serve', but encountered an error message: https://i.sstatic.net ...

Tackling the firestore batch limit issue within cloud functions

I am facing an issue when attempting to remove entire user records from firestore using cloud functions and receiving the following error message INVALID_ARGUMENT: The maximum allowed writes per request is 500 Is there a workaround for this problem? c ...

When trying to incorporate aws-sdk into Angular2, an error message stating "Module 'stream' cannot be found" may occur

I encountered the following issues: Error TS2304: Cannot find name 'Buffer', https://github.com/aws/aws-sdk-js/issues/994 and Using aws-sdk with angular2 Even though my typings and @types/node seem to be properly installed, I am still encount ...

Struggling to properly implement an "Errors" Object in the state function of a React Login Form Component

The issue arose while I was following a React tutorial. My objective is to develop a basic social media web application using Firebase, React, MaterialUI, and more. I am currently at around the 5:40:00 mark and have successfully resolved all previous pro ...

Initializing the ngOnInit function with 'this' keyword

I've encountered a scope issue where the lines "this.catVotes = catData" are within another function, preventing me from directly assigning it to "catVotes: Number;" Any suggestions on how I can overcome this challenge? catVotes: Number; dogVotes: N ...

Verification of custom data type validation

I am puzzled by the behavior of this custom type state: interface DataType { [key: string]: string;} const [data, setData] = React.useState<DataType>({}); When I attempt to execute console.log(data === {}) It surprisingly returns false. Why ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

Encountered an issue during the migration process from AngularJS to Angular: This particular constructor is not compatible with Angular's Dependency

For days, I've been struggling to figure out why my browser console is showing this error. Here's the full stack trace: Unhandled Promise rejection: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependen ...

What is the proper way to manage the (ion select) OK Button?

Hey there, I'm working with an Ionic select directive and I need to customize the functionality of the 'OK' button. When I click on it, I want it to call a specific function. I'm aware of the (ionChange) event, but that only triggers w ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

Utilizing pattern matching in switch statements

Imagine I have different APIs that provide data about various animals. Despite some shared properties, the JSON payloads for each animal type are quite unique and specific. To avoid chaos in my code, I am looking to create strongly typed TypeScript classe ...

Acquire the element within the observable

I have a code snippet that iterates through a list of Product objects. <div class="form-group" *ngIf="produtos != null"> <label class="form-control-label" for="produto">Product</label> <select class="form-control" id="produto" ( ...