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

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

What causes a compilation error to occur when a mapped type is invoked inside a class?

Below is a code snippet for review. An error occurs when calling the get method within the class, but works fine when called outside. Any thoughts on why? type DefinedKeys<T> = keyof { [K in keyof T as undefined extends T[K] ? never : K]: K } cla ...

Angular2, multi-functional overlay element that can be integrated with all components throughout the application

These are the two components I have: overlay @Component({ selector: 'overlay', template: '<div class="check"><ng-content></ng-content></div>' }) export class Overlay { save(params) { //bunch ...

Determining a value that increases to yield a fresh sum

I'm currently developing a character generator that determines your score based on the experience points you allocate to it. The scoring system is such that 1 XP gives you a score of 1, 3 XP gives you a score of 2, 6 XP gives you a score of 3, 10 XP g ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

Is there a way to recursively convert property types from one to another in an object that contains optional properties?

The scenario: I am currently working with MongoDB and a REST API that communicates using JSON. MongoDB uses objects instead of identifiers for documents, but when these objects are stringified (such as in a response body), they get converted into strings. ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

unable to utilize a tip with d3 version 5 in a TypeScript environment?

i'm facing an issue with the following code snippet: var tip = d3.tip() .attr('class', 'd3-tip') .attr('id', 'tooltip') .html(function(d) { return d; }) .direction('n ...

Ionic 5 Error: Unable to access 'subscribe' property of undefined object

Working with IONIC 5 service: import { HttpClient } from '@angular/common/http'; . . . getPlaces(placeId: string) { return this.httpClient.get( `https://test.com/offered-place/${placeId}.json`) } . . . Encountering an issue when tryin ...

A step-by-step guide to resolving the TS2345 compilation error during your TypeScript upgrade from version 4.7 to 4.8

We encountered a compiling error after upgrading from TypeScript 4.7.4 to a newer version (specifically, 4.8.4). This error was not present in our codebase when using 4.7.4. To pinpoint the issue, I have extracted the error into a small code snippet. When ...

Error: inability to execute performanceMeasurement.startMeasurement due to its absence in the function definition

An error occurred when attempting to login using @azure/msal-react in Next 13. Upon checking the error log, it was found that the error originated from the core library @azure/msal-react. Even after trying with a login popup, the error persisted. In my co ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Incorrect date generated by Moment.js from Unix timestamp

Is there a way to store unixtime as a Moment.moment state? Using moment(timestamp) seems to provide a different date. const [date, setDate] = useState<moment.Moment | null>(null); const timestamp = Math.floor(date.getTime() / 1000); setDate(m ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

What is the most efficient method for examining dependencies in Yarn 2 (berry)?

Is there a way to check for vulnerabilities in Yarn 2 dependencies? In Yarn 1.x, you could run yarn audit, similar to npm audit. However, this command is not available in Yarn 2. According to this issue on the Yarn berry Github, it may not be implemented ( ...

Encountering a premature closure error, specifically the inability to set headers after they have already been sent to the client, when trying to stream video

I am in the process of constructing a video streaming web server with Nestjs. I have diligently followed the steps outlined in the Nest documentation. Unfortunately, I encountered some errors... MY file.controller.ts import { Controller ...

Receiving an error while passing properties to a React component: "Property 'firstName' is not found on type 'Readonly<{}>'."

As a beginner in React, I need some patience I'm attempting to create a simple component where users can input their first and last names, update the values, and see them displayed after clicking a button. However, I keep encountering TypeScript comp ...