Trying to use a JS function within an Angular2 service but getting require is not a function in the console. I'm not sure how to include the external JS file. It's at the same directory level as the service using it.
- I believe that the declare statement is legit. true?
- I'm not sure how to handle the invalid require statement. It produces the
error "Require is not a function"
Service file: analytics.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
//how I thought i was supposed to make the JS function available
declare var AlchemyAPI: any;
@Injectable()
export class AnalyticsService {
constructor (private http: Http) {}
getResponse () {
//not sure how to handle this require. I know that its not allowed
though
var AlchemyAPI = require('./alchemyapi');
//instance of external JS file function
var alchemyapi = new AlchemyAPI();
var myText = "Whoa, AlchemyAPI's Node.js SDK is really great, I can't
wait to build my app!";
return this.http.get(alchemyapi.sentiment("text", myText, {}))
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body.data || { };
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server
error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
External JS file thaat makes remote API call: alchemyapi.js (at the same directory level)
var http = require('http');
var fs = require('fs');
//Make the class available
exports = module.exports = AlchemyAPI;