Calling a function outside of the constructor

Is there a different way to invoke a function from a service class without doing it in the constructor? I attempted to call the function outside of the constructor, but I wasn't able to get the result of ShowDanger from Toast.service.ts

For example:

toast.service.ts

export class ToastService {
  toasts: any[];

  show(textOrTpl: string | TemplateRef<any>, options: any = {}) {
    if (!this.toasts) {
      this.toasts = [];
    }
    this.toasts.push({ textOrTpl, ...options });
  }
  showDanger(dangerTpl: string | TemplateRef<any>) {
    this.show(dangerTpl, { classname: 'bg-danger text-light', delay: 5000 });
  }


Parent.service.ts

constructor(
private toastService = ToastService
)

get<T>(queryParams?, customEndpoint?: string): Observable<T> {
        let httpUrl = this.httpUrl;

        this.http.get<T>(
            `${httpUrl}`,
            { observe: 'response' }
        )
            .subscribe(resp => {
            },
                err => {
                    if (err.status === 400) {
                        this.toastsService.showDanger('Input Error');

                    } else if (err.status === 500) {
                        this.toastsService.showDanger('Communication Error');

                    } else {
                        this.toastsService.showDanger('Network Issues');
                    }
                }
            );
         }

Child.service.ts

export class ChildService extends ParentService {

 constructor(toastsService: ToastService) {
    super(toastsService);
  }
}

Answer №1

Modify the constructor in parent.service.ts to the following:

constructor(private toastService: ToastService)

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

The requirement is for TypeScript to be cast as Partial<T>, with the condition that the keys

I'm currently looking for two different utility types: one that consists of a subset of a type with matching value types, and another that only requires the keys to exist in another type. I've devised the following solution, which appears to be ...

Transform Angular into a library

I've been exploring different options but still haven't nailed down the best approach. I've developed an Angular library with custom components, which I'm converting into Web Components to be used in non-Angular applications. But to mak ...

Is it possible to utilize BE-provided Enum in the FE and if so, how can

How can I utilize the Enum from BE in an HTML template? Should I use it as is, or provide another one in FE? What is considered best practice? export interface UserModel { id?: number; email?: string; password?: string; gender?: UserModel ...

Typescript error: The property "Authorization" is not found in the type HeadersInit

As I utilize the npm module node-fetch, I have a helper function specifically designed to facilitate authorized requests to a third-party service. This function essentially acts as middleware by incorporating the Authorization header. async function makeAu ...

Utilizing Angular http.post to retrieve data from Cloud Function via POST request

Trying to send a POST request to a Google Cloud Function from Angular using @angular/common/http. The documentation for Angular http v7 lacks comprehensive examples, with no information on how to include data or objects in the request. Angular code snippe ...

Troubleshooting issue with absolute paths in Vite project using React and TypeScript

I'm having trouble implementing absolute paths in a Vite react-ts project. This is how I set up the project: npm init @vitejs/app npx: installed 6 in 1.883s √ Project name: ... test-vite √ Select a framework: » react √ Select a variant: » rea ...

Concealing the BottomNavigation bar in Nativescript

Currently using Nativescript 7+ and seeking to implement a feature where the TabStrip can be hidden on certain pages post navigation. Below is the relevant section of my .html code. <BottomNavigation id="bottomNav"> <TabStrip> ...

What is the method for utilizing Tuple elements as keys in a Mapped Type or template literal within typescript?

Is there a specific way to correctly type the following function in TypeScript? Assuming we have a function createMap() that requires: a prefix (e.g. foo) and a tuple of suffixes (e.g. ['a', 'b', 'c']) If we call createMap(& ...

What is the preferred method for validating an Angular form - ng-model or form input name?

When it comes to validating an input field and providing feedback, there are two methods that I have noticed: <form name="myform" ng-submit="myform && myFunc()"> <input name="foo" ng-model="foo" ...

Error in VS Code related to Vue Array Prop JSDoc TypeScript: The properties of type 'ArrayConstructor' are not found in type 'MyCustomType[]'

After reading the article "Why I no longer use TypeScript with React and why you might want to switch too", I decided to work on a Vue CLI project using ES6 without TypeScript. Instead, I enabled type checking in Visual Studio Code by utilizing JSDoc / @ty ...

Guide to integrating Mongoose typings with Angular 2 webpack starter

As a newcomer, I'm hoping this issue is straight forward. I am currently utilizing the angular2-webpack-starter found on GitHub. Based on the mongoose documentation, it appears that including their JavaScript file allows for accessing a global varia ...

Navigating through pages: How can I retrieve the current page value for implementing next and previous functions in Angular 7?

Greetings, I am a new learner of Angular and currently working on custom pagination. However, I am facing difficulty in finding the current page for implementing the next and previous functions. Can anyone guide me on how to obtain the current page value? ...

Incorporate form information into an array in Angular Version 2 or higher

This form is where I craft my questions https://i.sstatic.net/93781.png When composing a question, the ability to include multiple alternatives is available. There will also be an option to edit these alternatives. The desired format for my array is as ...

Is there a way for me to retrieve a variable from the response of a service that was defined within the same class in Angular 4?

import {Component, OnInit} from '@angular/core'; import {LoginService} from "../../services/login.service"; import {LoginUser} from "../../services/model"; @Component({ selector: 'login-component', templateUrl: './login.component. ...

What could be the reason behind the malfunction of nativescript-phone on Android during plugin build?

I am encountering a particular build error while trying to deploy our NativeScript app on my Android Studio Emulator: > Failed to build plugin nativescript-phone : Error: spawn ./gradlew ENOENT Exception in thread "DisconnectableInputStream source ...

Having difficulty implementing Angular 4 redirection for transitioning from old hash URLs to new non-hash URLs

In our single page application, we originally had a simple tab structure where each tab click led to a corresponding #url. Examples: , After transitioning to Angular 4, the urls no longer contain hash symbols. They now look like this: , I have added the ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Angular allows for the easy population of an array into an input box

I've been given a task to create 10 different input forms and populate them with an array of 10 users using Angular's looping functionality. By the end of this task, I expect to have 10 input forms filled with various user data from the array. ...

Discover the best practices for implementing services within the import decorator of an angular module configuration

Is there a way to access a service inside the load module in Angular, especially when the module is loaded from a decorator and the service is not yet DI? You can refer to this answer for an example. For instance, if the method in the service returns an ...

Challenges with invoking functions within ngFor loop during unit testing in Angular 12

I am currently learning about unit testing and I am facing an issue with calling a function inside an *ngFor loop in an Angular 12 application. I have an observable that contains an array of objects and it is working correctly, iterating through the data p ...