user3075338
user3075338

Reputation: 93

Ensure a service is done before going furthure

I need to ensure that my service is done before going to other functions as I need its result to be used. I have seen some solution, like this, but did not work.

here is what I code:

My service:

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

I called it as follows in ngOnInit:

ngOnInit()
{


    let spaceIndex=0;
    this.readJsonService.getText().subscribe((data) => {

         for (const line of data.split(/[\r\n]+/)){
        //   console.log(line);
           spaceIndex=line.search(/\s/);
        //   console.log("spaceIndex  " + spaceIndex)
           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();
}

and in tryThis() function, I want to log the result, which is in weakness that is a global interface. like so:

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

but it first runs the Trythis() function, so gives an empty array and says the length is 0, while running yet the service. and then logs the array from the ngonInit functiom. please please help. thank you in advence.

Upvotes: 0

Views: 61

Answers (2)

Seba Cherian
Seba Cherian

Reputation: 1793

Life-cycle hooks doesn't exist on injectables. So instead of using life-cycle hooks like ngOnInit in @Injectables, use the constructor.

@Injectable()

  constructor() {
      //your code
  }

Upvotes: 0

Abhishek Sharma
Abhishek Sharma

Reputation: 329

Place the statement ' this.trythis();' as follows,

    ngOnInit() {


        let spaceIndex=0;
        this.readJsonService.getText().subscribe((data) => {

             for (const line of data.split(/[\r\n]+/)){
            //   console.log(line);
               spaceIndex=line.search(/\s/);
            //   console.log("spaceIndex  " + spaceIndex)
               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();
           });



}

Upvotes: 1

Related Questions