Detect whether Angular is loaded on a page when using Systemjs

血红的双手。 提交于 2019-12-22 06:28:36

问题


UPDATE:

This question was specifically talking about Angular 2, and is now out of date. At the time of posting, there was not a way to detect whether it was loaded on the page. I have not tested other version, but Angular 8 now has an easy way to detect this and has been pointed out in the answer below.


I'm trying to figure out a good (preferably the best) way to detect whether or not Angular is loaded on the page.

I took a look at this question: Ways to Detect whether AngularJS is loaded in the current page or not, but the answer simply states to use window.angular, which is the first thing I tried (long before finding that answer.) It seems as though systemjs is causing Angular to not be in the global (window) scope.

Here is the head of my html file:

<script src="client/node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="client/node_modules/systemjs/dist/system.src.js"></script>
<script src="client/node_modules/rxjs/bundles/Rx.js"></script>
<script src="client/node_modules/angular2/bundles/angular2.dev.js"></script>
<link rel="stylesheet" href="client/styles/main.css"/>

<script>
  System.config({
    packages: {        
        client: {
            format: 'register',
            defaultExtension: 'js'
        }
    }
  });
  System.import('client/app')
        .then(null, console.error.bind(console));
</script>

Based on this question, and my understanding of http2, I don't see a real reason to not use systemjs.

Obviously, I may be wrong, systemjs may not be the cause of the issue; regardless, window.angular returns undefined even though I'm looking at my Angular app.

To give you our use case, in case it helps, we are loading an angular app via an init file that will be used on other websites (where we don't control the page in most cases.) We want our init file to be able to detect whether angular2 (and the proper version) among other dependencies are already included on the page. If they are not, we are dynamically adding what they don't have for our need. (There may be some other issues with this approach, but we'll tackle those issues when we get there.)

Summary

  1. We need to detect whether Angular is loaded on the page, and what version.
  2. Using systemjs, window.angular is returning undefined.
  3. The Angular app runs fine and without issue.
  4. With http2, we don't see the need to not load Angular using systemjs, but we are not opposed to changing that if necessary.

回答1:


I had success detecting Angular2 using:

window.ng


来源:https://stackoverflow.com/questions/34779126/detect-whether-angular-is-loaded-on-a-page-when-using-systemjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!