0

I'm using a third party JS I'm calling from Angular:

import { Component } from '@angular/core';
declare var SomeApi: any;

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstName: string;

  onStartTest() {
    SomeApi.runTest();    

    function onTestCompleted(testResult) {
      //Can get testResult.FirstName
      this.firstName = testResult.FirstName;
    }
  }      
}

I can successfully run the SomeApi.runTest() in Angular and when it finished I can get the testResult and its properties like FirstName and display to HTML. But the problem is I can't pass this to the local Angular variable which is firstName: string in this case. The component I think finishes up as the .runTest() runs in async.

I also tried running a service inside the function so that I can pass the data to a service after onTestCompleted():

constructor(private dataService: DataService) {}

function onTestCompleted(testResult) {
  //Can get testResult.FirstName
  this.firstName = testResult.FirstName;

  this.dataService.writeResult(testResult.FirstName);
}

But the problem is that an error comes out saying that .writeResult() is not known. I think it's because the life of the Component has ended?

I just want to ask for help on how I would get the testResult object and its properties outside function()?

DotDauz
  • 11
  • 5

1 Answers1

0

I think third party API that compatible with Angular 2 support observable,

try using subscribe instead of waiting the test to finish and then passing the result value to a function, like this:

SomeApi.runTest().subscribe(testResult => {
   this.firstName = testResult.FirstName;
   ...
});

or you can use promise as well, like this:

var dataPromise = SomeApi.runTest();
dataPromise.then(function(result) {
   // this is only run after runTest() resolves
   this.firstName = testResult.FirstName;
   ...
});
Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42
  • I actually tried putting .subscribe() at first but when I run the app it's giving me a 'Cannot read property 'subscribe' of undefined'. The same with putting .then(). Is this a sign that the JS I'm calling doesn't support observables? – DotDauz Oct 23 '17 at 05:55
  • yes, what is the API you are using, it is a third party or you had made it. – Ebraheem Alrabeea Oct 23 '17 at 11:57
  • It's a third party one. Is it possible to wrap the API so it returns a Promise? I'm also trying that one. – DotDauz Oct 23 '17 at 20:28
  • Can you tell what library are you using so that I check if it possible to wrap the API – Ebraheem Alrabeea Oct 23 '17 at 21:03
  • I think I've found a solution here: https://stackoverflow.com/questions/35296704/angular2-how-to-call-component-function-from-outside-the-app It's more like how the JS callback is returned. It's near to what I'm trying to do. But thanks for the replies. – DotDauz Oct 25 '17 at 00:53