Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traverson.js integration into Angular2 app

Has anyone successfully integrated traverson into an Angular2 app? If so, is there a step-by-step available?

Trying to integrate traverson.js into an Angular2 app for HATEOAS traversal. Attempted pulling in traverson.js per this technique (https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1#.9qx93kgki).

Run into dependency problems, starting with traverson's use of "require()". typical error:

Uncaught Error: Module name "minilog" has not been loaded yet for context: _. Use require([])

Also tried using ngUpgrade to bring in traverson-angular (angular 1.x based module), and ran into more dependency problems...

like image 296
Stephen DeMoor Avatar asked Mar 18 '26 08:03

Stephen DeMoor


1 Answers

I managed to simply install traverson and use it in an angular service:

npm install traverson

And then, in your service:

// imports

const traverson = require('traverson');

@Injectable() 
export class Service { 
   public getData(): Observable<Data> {
      const promise: Promise<Counterparty> = new Promise((resolve, reject) => { 
         traverson 
         .from('http://my-api.com') 
         // Add your traverson options here
         .follow('link', 'other-link')
         .getResource((error, data) => { 
              if (error) { 
                reject(error); 
              } else { 
                resolve(data); 
              });
      }
      return Observable.fromPromise(promise); 
   }
}

The problem here is that there is no up-to date typings for traverson yet so you have an hybrid JS/TS code.

I did not manage to use observables directly that's why I pass by a promise, which is much simpler by the way.

Note that traverson uses its own http client. If you want to use the angular http client, you need to create a bridge class, that implements the following methods:

get(uri: string, options: any, callback: (err, response) => void);
del(uri: string, options: any, callback: (err, response) => void);
post(uri: string, options: any, callback: (err, response) => void);
put(uri: string, options: any, callback: (err, response) => void);
patch(uri: string, options: any, callback: (err, response) => void);

The options are the traverson options.

Hope this helps

like image 136
William Gorge Avatar answered Mar 19 '26 21:03

William Gorge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!