What is the best way to invoke a function in a class from a different class in Angular 6?

Below is the code snippet:

import { Component, OnInit, ViewChild } from '@angular/core';
import { AuthService } from '../core/auth.service';
import { MatRadioButton, MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { SelectionModel } from '@angular/cdk/collections';
import { OrdersService } from '../orders.service';

export interface DataTableItem {
  ordersn: string;
  order_status: string;
  update_time: number;
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {
  radioValue: number;
  dataSource = new UserDataSource(this.orderService);
  selection = new SelectionModel<any>(true, []);

  // Sorting and pagination
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  // Columns displayed in the table. Columns IDs can be added, removed, or reordered.
  displayedColumns = ['ordersn', 'order_status', 'update_time'];

  // Filter
  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  // Checks if all rows are selected
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  // Toggles between selecting all rows and clearing selection
  masterToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.dataSource.data.forEach(row => this.selection.select(row));
  }

  constructor(public auth: AuthService, private orderService: OrdersService) {
  }

   
  onSelectionChange(radioSelection: MatRadioButton) {
    this.radioValue = radioSelection.value;
    console.log(this.radioValue);
  }

  ngOnInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
  }
}

export class UserDataSource extends MatTableDataSource<any> {
  constructor(private orderService: OrdersService) {
    super();

    this.orderService.GetOrdersList().subscribe(d => {
      this.data = d.orders;
    });
  }

  radioFilter() {
    const array = [];

    this.orderService.GetOrdersList().subscribe(d => {
      for (const entry of d.orders) {
        if (entry.order_status === 'READY_TO_SHIP') {
          array.push(entry);
        }
      }

      this.data = array;

      console.log(array);
    });
  }
}

I want to invoke radioFilter() from within HomeComponent. Here's what I've attempted so far:

  • Tried using @ViewChild in HomeComponent, but encountered the following error: Class 'UserDataSource' used before its declaration.
  • Imported UserDataSource and included it in the constructor of HomeComponent. This resulted in an error: Getting Uncaught Error: Can't resolve all parameters for HomeComponent

I'm currently stuck and seeking suggestions. Any help would be highly appreciated. Thank you!

Answer №1

Encountering Uncaught Error: Unable to Resolve All Parameters for HomeComponent

To address this issue, it is important to ensure that your dataSource is properly registered within an ngModule as injectable. Without being registered, it will not be able to be injected into the constructor of the HomeComponent. Additionally, considering that ngMaterial-dataSources are stateful, it is recommended to avoid using injectables for such stateful elements.

Error Regarding 'UserDataSource' Being Used before Its Declaration

The error you are experiencing suggests that the UserDataSource is being used prior to its declaration. It is essential to note that the UserDataSource should be included as a ViewChild in the component's template, rather than just an object without an associated HTML template. Since TypeScript processes annotations during compile/transpile time, the class declaration must precede its usage. One solution would be to move the declaration above the HomeComponent, or alternatively, create a separate file for the class and import it accordingly.

Potential Solution to Address the Issue

If you encounter difficulties calling the radioFilter method, remember that it is a public method within the UserDataSource class, and there exists an instantiated object named dataSource in the HomeComponent. The key is to refrain from calling the method in the constructor, as member variables are processed after the constructor execution. Consider invoking dataSource.radioFilter() outside of the constructor to mitigate this problem effectively.

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

Unable to establish a simulated environment and trial period for experimentation

I encountered the following errors during the test: TypeError: Cannot read properties of undefined (reading 'subscribe') Error: <toHaveBeenCalled> : Expected a spy, but got Function. I am having trouble understanding these errors. Here i ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

Exploring methods to trace the factory's property that is receiving updates from another factory within AngularJS

Hey there, I'm new to Angularjs and I have a bunch of factories in my application. The situation is, let's say we have obj1 in factoryA. Whenever I console.log(obj1), it displays numerous properties associated with it. This object is being update ...

What is the Reason FormControl#valueChanges Subscriptions are Not Cleaned up by Garbage Collection?

After reading numerous discussions, I've learned that it's important to unsubscribe from `FormControl#valueChanges` in order to avoid memory leaks. I now understand the importance of knowing when and how to unsubscribe from Observables, especiall ...

Improve loading speed of thumbnail and full images in HTML

I'm struggling with slow loading images on my blog website. Can anyone help me figure out how to improve loading speed and: Is it possible to use a separate thumbnail image that is smaller in size instead of the full image for both thumbnails and th ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expecte ...

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

JavaScript Promise Synchronization

I have a JavaScript function that returns an object using promises. The first time the function is called, it fetches the object, but for subsequent calls, it returns a cached instance. To simulate the fetching process, I've added a delay. var Promis ...

When the button is pressed, the TypeScript observable function will return a value

Check out the snippet of code I'm working with: removeAlert() : Observable<boolean> { Swal.fire({ title: 'delete this file ?', text: 'sth', icon: 'warning', showCancelButton: true, ...

What is the method for defining a monkey patched class in a TypeScript declarations file?

Let's say there is a class called X: class X { constructor(); performAction(): void; } Now, we have another class named Y where we want to include an object of class X as a property: class Y { xProperty: X; } How do we go about defining ...

Attention: issue TS18002 has been detected - The 'files' configuration file is currently blank

I'm currently working with TypeScript version 2.1.5.0. My setup includes the grunt-typescript-using-tsconfig plugin, but I'm encountering an error when running the task. The issue seems to be related to the property "files":[] in my tsconfig.jso ...

Next.js Error: Inconsistent text content between server-rendered HTML and hydration. Unicode characters U+202F versus U+0020

Having issues with dates in Next.js development. Encountering three errors that need to be addressed: Warning: Text content did not match. Server: "Tuesday, January 24, 2023 at 11:01 AM" Client: "Tuesday, January 24, 2023 at 11:01 AM" ...

The functionality of Ajax is currently disabled on the latest mobile Chrome browsers

I have successfully created a modal form with dependent dropdown lists, and I am populating these lists using an ajax call. The functionality works smoothly on desktop browsers and most mobile browsers, but there seems to be an issue on certain newer versi ...

Direct users from one path to another in Express framework

I have two main routes set up in nodejs. First is the users.js route: router.post('/users/login', function(request, response) { // Logic for user login // Redirect to dashboard in dashboard.js file after login response.redirect(&ap ...

AngularJS: Click on image to update modelUpdate the model by clicking

I am a newcomer to AngularJS and I am attempting to update my model after the user clicks on an image. Below is the code for this: <div class="col-xs-4 text-center"><a ng-model="user.platform" value="ios"><img src="ios.png" class="img-circl ...

Exploring the use of MediaSource for seamless audio playback

Currently working on integrating an audio player into my Angular web application by following a tutorial from Google Developers and seeking guidance from a thread on Can't seek video when playing from MediaSource. The unique aspect of my implementati ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

Issue encountered when attempting to activate a Vue function in order to update a specific component's field

Let me preface this by saying that I am new to Vue.js and still learning the ropes. Here's what I'm trying to achieve: I have a label and a button. The behavior I want is that when the label is not visible, the button should display "Show Label" ...