Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component-to-component calling, leaving confusion in understanding.

Here is an example:

Testcomponent.ts
@Component({
  selector:'component'
})
export class Testcomponent{

  test(){ 
    console.log('test method');
  }
}
Testservice.ts
@Injectable()

export class Testservice {

private testcomp: Testcomponent;

// service method
dummy(){
  //trying to call component method
  testcomp.test();
  }
}

This approach of calling the component method raises doubts about its correctness. Assistance is needed to understand the proper way to achieve this task.

Further research on Stack Overflow did not provide a clear understanding: How to call component method from service? (angular2)

Answer №1

Check out the code snippet below for an example. You can also find more information at this link

export class ExampleComponent {

  constructor(private exampleService: ExampleService) {
    this.exampleService.exampleComponent$.subscribe(res => {
      this.exampleMethod()
    })
  }

  exampleMethod() {
    console.log('This is an example method');
  }
}

export class ExampleService {

  private exampleComponentSource = new Subject<boolean>();

  // Observable string streams
  exampleComponent$ = this.exampleComponentSource.asObservable();


  // Service method
  dummy() {
    // Trying to call a component method 
    this.exampleComponentSource.next(null);
  }
}

Answer №2

To properly import a subject and emit values from a service, follow these steps:

@Injectable()
import { Subject } from 'rxjs';

export class DataService {

  dataSubject = new Subject();


// Service method
sendData(){
      this.dataSubject.next('hello from service');
  }
}

In your component, subscribe to the event like so:

@Component({
  selector:'app-component'
})
import {DataService}  from 'data.service';
export class AppComponent{
        constructor(private dataService: DataService) {
   }

  fetchData(){ 
  this.dataService.dataSubject.subscribe((data)=>{
   console.log(data);
    });

  }
}

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

Changing a method within a class does not automatically update how it is used in other classes that inherit from it

I am attempting to modify the alpha method in the context of the Cat class, and have the beta method reflect those modifications. const wrapperFn = <T extends (...args: any) => any> (a: T) => { return (...args: Parameters<T>) => ...

"Implementing Two-Way SSL with Angular 2 and BrowserSync

Currently, I am working on an Angular2 application that requires two-way SSL authentication. This means that the browser needs to present a valid (PFX) certificate in order to access the application. For deployment, I am using lite-server (which utilizes B ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

Require users to sign in immediately upon landing on the homepage in Next JS version 13 or 14

I have created a traditional dashboard application using Next.js 13 with a pages router that places all pages behind the /dashboard route, such as /dashboard/users, /dashboard/orders, and so on. I want to ensure that when a user visits the website, a fork ...

What is the process for obtaining the resolved route data value?

Within my route configuration, I have a resolve that retrieves user JSON data. const routes: Routes = [ { path: 'profile/:id', component: ProfileEditComponent, pathMatch: 'full', canActivate: [AuthGuard], resolve: { use ...

Show the alias of a type in Vscode Typescript instead of its definition

Here is some code that I am working with: type Opaque<T,U> = T & {_:U}; type EKey = Opaque<number,'EKey'>; type AKey = Opaque<EKey,'AKey'>; type PKey = Opaque<AKey,'PKey'>; let a = <PKey>1; ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, i ...

Webpack and typescript are encountering a critical dependency issue where the require function is being utilized in a manner that prevents static extraction of dependencies

Having recently started diving into typescript and webpack programming, I must admit that my background in this area is limited. Despite searching through similar questions on Stack Overflow, none of the solutions provided so far have resolved my issue: I ...

Designing a popup using Angular, CSS, and Javascript that is capable of escaping the limitations of its parent div

I'm currently working on an Angular project that involves components nested within other components. My goal is to create a popup component that maintains the same size and position, regardless of where it's triggered from. One suggestion I rece ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Angular HTTP client failing to convert response data to specified type

Recently, I started using the new HttpClient and encountered an issue where the response is not cast with the provided type when making a call. I attempted to use both an interface and a class for casting, but it seems that only interfaces work as shown in ...

Asynchronous data binding in Angular 2

I'm trying to pass a value from my ImageDetail component to the ImageComment component as follows: ImageDetailHtml: <image-comment [photo]="photo"></image-comment> ImageCommentComponent: export class ImageCommentComponent { @Input(&a ...

Tips on showing validation error message through a tooltip when hovering over the error icon in Ionic

Currently, I have implemented bootstrap validation within my Ionic application and it is functioning correctly. The error icon appears within the textbox along with the error message below the textbox. However, I am interested in changing this setup so t ...

Unregistered outlet name unrecognized

I am currently working on developing a tabs component within one of my components, utilizing named outlets for this purpose. At the moment, I have my default outlet set up to display each page, and I would like to incorporate a named outlet within one of ...

Show pictures in Angular 10 after uploading them via Multer on the Node.js server

My web application is built using the MEAN stack. I am utilizing Multer to save images in an artImages folder on my Node.js server. The post request uploads images and stores their paths along with other data in MongoDB. const storage = multer.diskStorage( ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Unlocking the potential of nested conditional types in TypeScript

The source of the autogenerated type below stems from a GraphQL query: export type OfferQuery = { __typename?: 'Query' } & { offer: Types.Maybe< { __typename?: 'Offer' } & Pick<Types.Offer, 'id' | 'nam ...