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:
- My aspect: https://github.com/loki2302/angularjs-experiment/blob/master/angular2-experiment/src/logging.aspect.ts
- My Angular module: https://github.com/loki2302/angularjs-experiment/blob/master/angular2-experiment/src/app.module.ts
- A component I want to apply it to: https://github.com/loki2302/angularjs-experiment/blob/master/angular2-experiment/src/calculator.component.ts
- A service I want to apply it to: https://github.com/loki2302/angularjs-experiment/blob/master/angular2-experiment/src/calculator.service.ts
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!
- Removing my imports and adding
import './logging.aspect'
into app.module.ts indeed did the trick. - 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:
git clone https://github.com/loki2302/aspectjs-angular-experiment.git
npm i
npm run-script run
- Go to http://localhost:8080
- Open JS console in dev tools
- Click the "Increment" button and see how it says BEFORE, INSIDE, AFTER in console.
- 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.
- 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.