I'm creating an Angular 2 app where I have a component which is supposed to render a list of data to the corresponding view. The data is to be loaded in through a service from a JSON file which is supposed to get its data from a javascript function which is a web scraper. This javascript function should be called when the component is initialized after which the service will be started.
I've looked everywhere on SO and other places but haven't found a definitive way to execute a javascript function from a component. The closest approach I found was in this SO post which implements a typescript interface in order to load the javascript function. The issue is that it isn't clear from the post what the javascript function is or how it needs to be used in the component. In my case, I need to call the request()
method which I've 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 of 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 ngOnInit()
function inside of 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 the correct usage for the interface here because its hard to tell from the typescript docs
I think I might be on the right track here, but I'm not really sure. How should I be implementing the interface to execute the request()
method on initialization of the component?