Angular 2: calling Javascript function from typescript

I am creating an Angular 2 application where I have a component that should display a list of data in an appropriate view. Data should be loaded through the service from a JSON file, which should receive its data from the javascript function, which is a web scraper. This javascript function should be called when the component is initialized, after which the service will start.

I looked everywhere at SO and other places, but did not find a final way to execute a javascript function from a component. The closest approach I found was in this SO post , which implements the typescript interface to load the javascript function. The problem is that the message is not clear what the javascript function is or how it should be used in the component. In my case, I need to call a method request()that I encapsulated in the following class based on this tutorial :

Scraper = function(url){
request(url, function(error, response, html){
    if(!error){
        var $ = cheerio.load(html);

    var title, release, rating;
    var json = { title : "", release : "", rating : ""};

    $('.header').filter(function(){
        var data = $(this);
        title = data.children().first().text();            
        release = data.children().last().children().text();

        json.title = title;
        json.release = release;
    })

    $('.star-box-giga-star').filter(function(){
        var data = $(this);
        rating = data.text();

        json.rating = rating;
    })
}
fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){

    console.log('File successfully written! - Check your project directory for the output.json file');

})

// Finally, we'll just send out a message to the browser reminding you that this app does not have a UI.
res.send('Check your console!')

    }) ;
}

Inside the typescript file, I was thinking of implementing something like this:

interface Scraper {
    request: INIT;

}
interface INIT {
    init: Function;
}
declare var Scraper: Scraper;

and then in the function ngOnInit()inside the component class:

ngOnInit(): void{
       //Calling javascript function?
        Scraper.request.init();

       //Service to load JSON
        this._productService.getProducts()
            .subscribe(products => this.products = products,
            error => this.errorMessage = <any>error);
    }

I have no idea if this is right for the interface here, because it's hard to say from typescript docs

, , . request() ?

+4

Source: https://habr.com/ru/post/1650361/


All Articles