Search code examples
javascriptangularasp.net-core-webapiangular2-changedetectionasp.net-authorization

Angular infinite change detection loop caused by oidc-client library


I copied the solution people posted on github linked below, check it out for further comments by library creators, if they ever solve this.

I'm writing an Angular app, using version 12. I opened up Angular devtools and found that I have ~150 change detection cycles each second, nonstop.

It's worth mentioning that it is an ASP.NET Core WebAPI app, which comes with ApiAuthorizationModule that adds logic and elements regarding login, logout, navigation etc. I can't prove it definitely, but everything points to it being the root cause.

Cycle 578

Cycle 579

Each passes through different components, but they all have the source in common:

Window.addEventListener:message

Can anyone explain this behavior? Or at least point me in the right direction? I've got absolutely no idea what causes this particular event to be added to window.

I do get this error message in regular Chrome console:

Content Security Policy of your site blocks the use of 'eval' in JavaScript` The Content Security Policy (CSP) prevents the evaluation of arbitrary strings as JavaScript to make it more difficult for an attacker to inject unathorized code on your site. To solve this issue, avoid using eval(), new Function(), setTimeout([string], ...) and setInterval([string], ...) for evaluating strings.

Maybe all of this has something to do with some silent refresh or something, I think they're related somehow? https://github.com/manfredsteyer/angular-oauth2-oidc/issues/785

[EDIT]: Now that I've read through this entire github thread, yeah, that's exactly the issue. Any tips on where to put this command from original post this.ngZone.runOutsideAngular(() => {...}?


Solution

  • The solution, as seen on the github link form my question, is to disable zone patches for message event and hope that creators of the library will solve the bug at some pont. I followed the advice and created zone-patches.ts like this:

    (window as any).__Zone_ignore_on_properties = [
      {
        target: window,
        ignoreProperties: ['message'],
      },
    ];
    
    (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['message'];
    
    export { };
    

    And imported it in pollyfills.ts like so:

    import './zone-patches';
    import 'zone.js/dist/zone'; // Included with Angular CLI.
    

    Just make sure you respect the order and include your custom import before the zone itself.

    This leaves sporadic detection cycles caused by some setInterval somewhere, but it's a few cycles per second so - much better than before!

    If someone solves that one as well, please shoot a comment for the rest of us :)