How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file:

"scripts": [
    "node_modules/csspatternlibrary3/js/site-utils.js",
    "node_modules/csspatternlibrary3/js/svg-cache.js",
    "node_modules/csspatternlibrary3/js/svg-url.js"
]

Furthermore, in order for the svg icons to be accessible, the method

brandcpl.initializeAllSvgIcons();
needs to be invoked. But the question remains - should an invocation similar to the following be included somewhere?

<script type="text/javascript">
  $( document ).ready(function() {
    brandcpl.initializeAllSvgIcons();
  });
</script>???

Upon invoking

brandcpl.initializeAllSvgIcons();
via console post app start, the newly added SVG icons become visible. However, the intention is to trigger this method during the loading phase of the application...

UPDATE

After following your suggestions:

  1. I appended:

    // included in app.module.ts under providers section: { provide: APP_INITIALIZER, useFactory: init, }

In my app.module.ts: ],

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: RequestInterceptor,
    multi: true,
  },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ResponseInterceptor,
      multi: true,
    },
    {
      provide: APP_INITIALIZER,
      useFactory: init,
    },
    AppService,
    LocalDataService,
    ValidationService,
  1. Added:

    // place above ngModule declaration or save it as a separate file.. export function init() { brandcpl.initializeAllSvgIcons(); }

In my home.component file:

import {Component, OnInit} from '@angular/core';
import {DataCenterService} from '@data-center/data-center.service';
import {Observable} from 'rxjs/internal/Observable';

export function init() {
  (window as any).brandcpl.initializeAllSvgIcons();
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  hasPermissionToReview$: Observable<boolean>;

However, encountering the subsequent errors:

    ERROR in ./node_modules/saucelabs/index.js
    Module not found: Error: Can't resolve './lib-cov/SauceLabs' in 'C:\Users\me\Documents\intellij_workspace\comp\edp-app\node_modules\sauce
    labs'
    ERROR in ./node_modules/protractor/built/debugger.js
    Module not found: Error: Can't resolve 'child_process' in 'C:\Users\me\Documents\intellij_workspace\comp\edp-app\node_modules\protractor\
    built'
    ERROR in ./node_modules/protractor/built/taskRunner.js
    Module not found: Error: Can't resolve 'child_process' in 'C:\Users\me\Documents\intellij_workspace\comp\edp-app\node_modules\protractor\
    built'
    ERROR in ./node_modules/protractor/built/runner.js
...
...

Seeking clarification on my procedure missteps.

Answer №1

Sure thing, you might want to consider using the app initializer approach.

// You can declare this function above the ngModule declaration or in its own file..
export function initializeApp() {
   brandcpl.initializeAllSvgIcons();
}

// In your app.module.ts file, add this to the providers array:
{
  provide: APP_INITIALIZER,
  useFactory: initializeApp,
}

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

In Angular 2 Type Script service, make sure to include the @angular/core module for proper functionality as the 'require' method may not

I am encountering an issue with a service I am using. Whenever I try to start the page, I receive an error message. Here is the screenshot of the error: https://i.sstatic.net/WMzfU.png The compiled .js file contains the following code: reuired('@ang ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Running into issues with TypeScript in conjunction with Redux-Form and React-Redux connect

My excitement for TypeScript grew until I encountered some frustrating incompatibilities between Redux-Form and React-Redux. I am aiming to wrap a component decorated with reduxForm using the connect decorator from react-redux—this method has always bee ...

Error TS2694 is being caused by Electron Typescript Material-UI withStyles because the namespace "".../node_modules/csstype/index"" does not have an exported member called 'FontFace'

While I am experienced with Material-UI, I am relatively new to Electron and using React, TypeScript, and Material-UI together. Recently, I encountered an error while attempting to create an electron boilerplate code for future project initialization. Init ...

Is Angular 2+ responsible for loading the entire module or only the exported components within it?

I'm dealing with a situation where I have a large module but only need to export one specific component. I'm wondering if Angular loads the entire module or just the exported components, as I want to optimize performance without compromising the ...

Ionic 2 - Error: Module ""."" not found at runtime

Encountered a perplexing error while running my Ionic 2 application on localhost using the command: ionic serve I've diligently inspected all my imports for any incorrect paths in my TypeScript files, but haven't found anything amiss. The only ...

The Angular Material Table is not showing any data on the screen

My challenge is to consolidate data from 4 different endpoints in order to generate a ListElement that will populate an angular material table. Despite receiving the correct data in my logs, the table remains empty. Interestingly, when I include a conditio ...

The specified property cannot be found in the type 'IntrinsicAttributes & ...'

I'm currently working on adding a custom prop to a custom styled-component: interface Props { image?: string; title?: string; subtitle?: string; background?: string; } export function CardWide({ image, title, subtitle, background }: Props) ...

Typescript and Apollo Client return types intertwined

My goal is to create a simple function within a class that generates an Apollo Client. Below is the code I have implemented: import appConfig from 'config/app-config'; import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/clie ...

The HTMLInputElement type does not contain a property named 'name'

function handleChange(e) { console.log(e.target.name); } <input name="bb" onChange={handleChange} /> Have you ever wondered why the HTMLInputElement element does not have a name attribute in React? ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Implementing data binding in ngStyle with Angular

Having trouble binding data with Angular 8, I attempted the following method: <div class="speed" style="background-image: url('http://example.com/assets/images/meter.png')" [ngStyle]="{'--p':result.percentage}"></div> The ...

I am developing a JWT authentication and authorization service for my Angular application. However, I am running into issues when trying to implement observables

I have created a user class and required interfaces as outlined below: user.ts import { Role } from '../auth/auth.enum' export interface IUser { _id: string email: string name: IName picture: string role: Role | string userStatus: b ...

What are the downsides of utilizing a global function over a private static method in Typescript?

It's quite frustrating to have to write this.myMethod() or ClassName.myMethod() instead of just myMethod(). Especially when dealing with a stateless utility function that doesn't need direct access to fields. Take a look at this example: functi ...

Adding a static global constant in webpack dynamically

I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons <md-tab-group> <md-tab label="Tab 1">Content 1</md-tab> <md-tab label="Tab 2">Content 2</md-tab> </md-tab-group> <button md-button (click)="showTab1()">Show Tab 1< ...

Display HTML tags on an HTML page using TypeScript

In my angular application, I encountered an issue where I needed to call one component inside another component. Initially, I was able to achieve this by simply using the second component's selector in the HTML of the first component: html: <div&g ...