Make sure the task is completed before proceeding any further

Before proceeding to other functions, it is crucial that my service is completed as I rely on its result. Despite trying various solutions, such as this one, I have not been successful.

Here is an example of the code:

The service being used:

  getText(){ return this.http.get(this.textURL, {responseType: 'text'}); }

I called it within the ngOnInit lifecycle hook like this:

ngOnInit()
{
    let spaceIndex=0;
    this.readJsonService.getText().subscribe((data) => {
         for (const line of data.split(/[\r\n]+/)){
           spaceIndex=line.search(/\s/);
           this.weakness.push({
             CWE_ID: line.substring(line.search('CWE-'), spaceIndex),
             weakness: line.substr(spaceIndex)
           })
          }
            console.log(this.weakness.length)
            console.log(this.weakness)
       });

 this.tryThis();
}

In the tryThis() function, I aim to display the result contained in the global interface 'weakness' with the following code:

  console.log(this.weakness.length); console.log(this.weakness)

However, the tryThis() function executes first, displaying an empty array and indicating a length of 0, even while the service is still running. It then logs the array from the ngOnInit function. I am seeking assistance with this issue. Thank you in advance.

Answer №1

Insert the code ' this.trythis();' at the specified location:

    ngOnInit() {


        let index=0;
        this.fetchDataService.getData().subscribe((data) => {

             for (const item of data.split(/[\r\n]+/)){
            //   console.log(item);
               index=item.search(/\s/);
            //   console.log("Index: " + index)
               this.items.push({
                 ID: item.substring(item.search('ID-'), index),
                 value: item.substr(index)
               })
              }
                console.log(this.items.length)
                console.log(this.items)

                this.trythis();
           });



}

Answer №2

When it comes to injectables, life-cycle hooks are not available. Therefore, in place of utilizing life-cycle hooks such as ngOnInit in @Injectables, opt for using the constructor.

@Injectable()

  constructor() {
      //your code
  }

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 structure of '({ path: string; redirectTo: string; pathMatch: string; } | { path: string; component: typeof Rec...' does not match the expected type 'Route[]'

I encountered an error while setting up my application's routes. The error message reads: "Type '({ path: string; redirectTo: string; pathMatch: string; } | { path: string; component: typeof Rec...' is not assignable to type 'Route[] ...

Mastering the Art of Handling Postgres Error Messages for Accurate Query Execution

Currently, I am utilizing pg and node.js. The issue arises when a user logs in through the auth0 widget, as I am passing the returned email to check against my database for existing users. If the user does not exist, I am inserting their information into t ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Adding a custom button to CkEditor 5 in Angular 12: Step by step tutorial

How can I customize the toolbar in version 4 of Ckeditor 5 by adding a unique button? I have tried looking through the documentation, but have been unsuccessful in achieving my goal. ...

Oops! It seems like there has been an issue. The EnjoyHint is not

Encountered the following error message: https://i.stack.imgur.com/JL4l6.png The error in my code is within the line that initializes a new EnjoyHint object. Seeking assistance to resolve this issue. public initiate(stepName) { const steps = ...

"I am having trouble calling the useStyles function in React with Typescript and Material-

There seems to be a problem with calling the useStyles function as it is throwing the following error message: This expression is not callable. Type 'never' has no call signatures.ts(2349) const useStyles: never Below is the complete code snip ...

using css styles in an angular component of a web application

I am currently developing an Angular 2 application with ASP.NET WebAPI 2 to retrieve data. Instead of using ASP.NET cshtml pages, I am utilizing HTML pages to display the content. Within my application project, I have two CSS files - Bootstrap.css and Site ...

What is the most effective method for handling numerous HTTP requests upon the initialization of an application?

Within my Angular application, I am facing the challenge of executing multiple (6) HTTP requests from different sources during initialization. Currently, I am using app_initializer and promise.all() to achieve this. However, the issue lies in the fact that ...

How can Angular 4 manage an object containing other objects most effectively?

Who can guide me on the best way to handle a data structure like this: { "1":{ "id":"1", "name":"Facebook", "created_at":"", "updated_at":"", "fields":{ "1":{ "id":"1" ...

Receiving and extracting JSON values by subscribing in Angular

I have a function in Angular 5 that sends data to the server: doLogin(){ var link = 'https://www.sportsmanager.us/Ionic/ASPPages/IonicRMLogin.asp?Login=T&O=2'; var myData = JSON.stringify({txtEmailAddress: this.txtEmailAddress,txtPasswor ...

Error: Unable to iterate through posts due to a TypeError in next.js

Hi there, this is my first time asking for help here. I'm working on a simple app using Next.js and ran into an issue while following a tutorial: Unhandled Runtime Error TypeError: posts.map is not a function Source pages\posts\index.tsx (1 ...

Pagination and Rowspan features malfunctioning in Material Table

Currently, I'm encountering a problem when trying to paginate a material table with rowspan. The binding of the rowspan attribute works correctly by itself. However, once pagination is implemented, it results in the duplication of values. For instance ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

Oops! There was an unexpected error: TypeError - It seems that the property 'title' cannot be read because it is undefined

HTML document example <ion-header> <ion-toolbar color="danger"> <ion-buttons> <button ion-button navPop icon-only> <ion-icon ios="ios-arrow-back" md="md-arrow-back"></ion-icon> </button> ...

Transmitting multiple parameters, including a file, from Angular to Spring framework

I am attempting to send an http request with multiple parameters to Spring. One of the parameters is a file, but I keep receiving a bad request error from the server. I am confident that I have made a mistake somewhere, and I would appreciate your assistan ...

Is there a way to retrieve all IDs within an array of objects using a foreach loop and merge the data associated with each ID?

I am currently working on a TypeScript API where I have merged all the data from this API with some additional data obtained from another API function. I have provided a snippet of my code which adds data to the first index of an array. M ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

Compiling a list of products, but the user interface needs some adjustments

Currently, I have designed a product list menu that includes a hover dropdown feature. This means that when a user hovers over a specific menu item, the corresponding list will automatically appear. However, I am facing two issues with this setup. Firstly, ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div ...

Align the ion content (or text or label) to the center vertically

I am striving to achieve a similar look as shown in the following images: https://i.sstatic.net/YFMay.png However, I am currently at this stage: https://i.sstatic.net/ZvpBV.png Please note that the first image showcases a bootstrap form, while the seco ...