mgechev / aspect.js

JavaScript library for aspect-oriented programming using modern syntax.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How do I apply aspect to multiple TS modules?

agibalov opened this issue · comments

All aspect.js usages examples I managed to find seem to only apply aspect in scope of single TS module: example. Is it for sake of simplicity or is it a technical restriction?

In my case, I wanted to apply an aspect to multiple classes, but I didn't manage to make it work without adding:

import {LoggingAspect} from "./logging.aspect";
LoggingAspect;

to every module. Here's my illustration:

How do I avoid these funny references? I would appreciate any hints.

You can do the following:

import './logging.aspect';

It is similar to importing Rx.js operators which produce some side-effect. The aspects do not have access to the ElementInjector, in order to get access to it you can use the Angular bindings for aspect.js. Notice that the code won't work with AoT because it is woven runtime, instead of compile time.

@mgechev thank you a lot!

  1. Removing my imports and adding import './logging.aspect' into app.module.ts indeed did the trick.
  2. And indeed DI doesn't seem to work with this approach. I unfortunately didn't manage to make things work with aspect.js-angular. After replacing aspect.js's @Wove() with aspect.js-angular's @Wove, it now says:
EXCEPTION: Uncaught (in promise): Error: Error in ./result class result_Host - 
inline template:0:0 caused by: Class constructor CalculatorService cannot be 
invoked without 'new'

Would you share a snippet which demonstrates your use case, so I can see what's wrong?

I've prepared a minimal example to demonstrate the issue: https://github.com/loki2302/aspectjs-angular-experiment - please feel free to:

  1. git clone https://github.com/loki2302/aspectjs-angular-experiment.git
  2. npm i
  3. npm run-script run
  4. Go to http://localhost:8080
  5. Open JS console in dev tools
  6. Click the "Increment" button and see how it says BEFORE, INSIDE, AFTER in console.
  7. Then update https://github.com/loki2302/aspectjs-angular-experiment/blob/master/src/app.module.ts#L6 - replace aspect.js import with aspect.js-angular import.
  8. Reload the page

In my case the page is empty and in console it shows the error I've mentioned above.

Thanks. I'll take a look and tell you what I find once I do.

Opened a PR here.