0

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.

  1. I believe that the declare statement is legit. true?
  2. 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;
Joel
  • 97
  • 2
  • 13
  • Are you sure the 'fs' of nodejs is going to work in browser? HTTP definitions are also different so you can do a `import * from 'http'` You might have to refactor the code. – Gary Aug 04 '16 at 03:19

2 Answers2

0

You can remove require and add JS file in script tag of you index.html. declare states typescript compiler that var/function with that name will be available at runtime so won't give compile time errors.

Arpit Agarwal
  • 3,993
  • 24
  • 30
  • Did that, and it removed the compile time error but now i get error TS2304: Cannot find name 'AlchemyAPI'. presumably from the class instantiation. – Joel Aug 04 '16 at 02:47
0

No need to use require. You could just import it like you did with @angular and rxjs:

import { AlchemyAPI } from './alchemyapi';

Now you can use AlchemyAPI inside your code anyway you want.

Bernardo Pacheco
  • 1,445
  • 1
  • 14
  • 23