【问题标题】:Convert $window.UserSettings array from angularjs component to angular 8 component将 $window.UserSettings 数组从 angularjs 组件转换为 angular 8 组件
【发布时间】:2020-12-04 16:08:09
【问题描述】:

我有一个 angularjs 1.7 组件,我需要升级到 angular 8 组件。它有一个外部脚本,我无法修改。该脚本将 iframe 插入到 div 中,并且它需要组件的一些设置来自定义 iframe。

旧组件代码:

angular.module('myApp.shared').component("userExternal", {
  template: '<div id="userIframe"></div>',
   controller: function ($window) {
      this.scriptUrl = "//myurl/widget/addIframe.js";
      this.$onInit = function () {
            $window.UserSettings = [];
            $window.UserSettings.push(['set', {
                btn_color: '#008A00',
                bg_color: 'white'
            }]);                
        });
     };
  }
});

我这里有两个问题:

  1. 我不知道如何将 $widnow 转换为 Angular 8 窗口对象。
  2. 当我将 $window 转换为 Angular 8 窗口时,如何向其中添加 UserSettings 数组?

这是我的 angular 8 组件,但我的代码无法正常工作。

HTML 模板

<script src="//myurl/widget/addIframe.js"></script>
<div class="user_external></div>

TS 代码

import { Component} from '@angular/core';    
@Component({
   selector: 'app-user',
   templateUrl: './user-external.component.html'
})
export class UserExternalComponent {
 constructor() {      
} 
ngOnInit() {
    window.UserSettings = [];
  
   window.UserSettings.push(['set', {
      btn_color: '#008A00',
      bg_color: 'white'
   }]);          

    console.log(window);
  }
}

谢谢

【问题讨论】:

    标签: angularjs angular angular8 angular-upgrade


    【解决方案1】:

    结合this tutorial 用于窗口参考和this tutorial 用于从AngularJS 升级到Angular,我创建了一个似乎可以完成工作的可注入服务,至少到目前为止在降级的上下文中是这样。 (下一步是开始升级使用依赖项的模块,但我成功地将 $window 的所有 AngularJS 注入替换为我的新 APIWindow 类,并且一切正常,没有中断错误。)

    请记住,这是在当前主要是 AngularJS 应用程序中用作降级的 Angular 类,该类如下所示:

    // api.window.service.ts
    
    import { Injectable } from '@angular/core'
    import { downgradeInjectable } from '@angular/upgrade/static'
    import * as angular from 'angular'
    
    // You could change this to return any property on Window, but external is the one I use:
    function _external (): any {
      return window.external
    }
    
    @Injectable()
    export class APIWindow {
      get external (): any {
        return _external()
      }
    }
    
    angular
      .module('APIModule')
      .service('APIWindow', downgradeInjectable(APIWindow))
    
    

    希望这可以帮助其他有类似情况的人遵循这条升级路径!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 2019-09-05
      • 2021-12-16
      • 2020-12-12
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多