【问题标题】:Is it possible to assign all module imports as a return type?是否可以将所有模块导入分配为返回类型?
【发布时间】:2017-02-19 16:27:24
【问题描述】:

我是 Typescript (1.8) 的新手。我正在将一个为 angular 1.4 编写的项目转换为 typescript。

我做的其中一件事是创建一个 D3Service,它异步加载 d3.js 库并使其在 Promise 中可用。

这是我转换成打字稿的代码:

namespace D3Provider{

    export class D3Service{
        static $inject = ['$document', '$window', '$q', '$rootScope','$timeout'];

        public d3: ng.IPromise<{}>;

        constructor(
            private $document: ng.IDocumentService, 
            private $window: ng.IWindowService, 
            private $q: ng.IQService, 
            private $rootScope: ng.IScope, 
            private $timeout: ng.ITimeoutService){
                var d = $q.defer();
                this.d3=d.promise;
                function onScriptLoad() {
                // Load client in the browser
                $timeout(function(){
                    $rootScope.$apply(function () {
                        d.resolve($window['d3']);
                    });
                });
            }
            var scriptTag = $window.document.createElement('script');
            scriptTag.type = 'text/javascript';
            scriptTag.async = true;
            scriptTag.charset="utf-8"
            scriptTag.src = 'bower_components/d3/d3.min.js';
            scriptTag.onload = onScriptLoad;

            var s = $document[0].getElementsByTagName('body')[0];
            s.appendChild(scriptTag);
        }
    }
    angular.module('d3', [])
    .service('d3Service', D3Service);
}

公共 d3 属性包含一个包含来自 window.d3 的值的承诺。

我已经下载了 ../../typings/modules/d3/index.d.ts 中的类型 file

在代码中,我尝试了以下操作:

/// <reference path="../../typings/modules/d3/index.d.ts" />

import * as d3lib from 'd3';
...
public d3: ng.IPromise<d3lib>;

然后编译器报错:错误 TS2304: 找不到名称 'd3lib'。

【问题讨论】:

  • 为什么不导入ng.IPromise&lt;d3&gt;
  • 或者,你试过this file?
  • 嗨@Paarth,也许我做错了什么,但是当我只使用引用时,没有导入并说 ng.IPromise,然后我收到错误“找不到名称 'd3 ’”。当我使用另一个文件时,我得到了同样的错误。
  • 我应该澄清一下。当您尝试这样做时,您是否删除了import * 行但保留在/// &lt;reference path 行中?这是我的建议
  • 是的,这确实给出了相同的结果。我在 d3.d.ts 文件中还看到它指示行 export = d3 为“duplicate identifier export ="

标签: angularjs d3.js typescript visual-studio-code typescript-typings


【解决方案1】:

或者,您可以使您的承诺无效(称其为 ready 或类似名称)并且当它解决时 - 您可以将 d3 作为全局变量/命名空间访问。

public ready: ng.IPromise<void>;

...

var d = $q.defer();
this.ready = d.promise;
var scriptTag = $window.document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.charset="utf-8"
scriptTag.src = 'bower_components/d3/d3.min.js';
scriptTag.onload = () => d.resolve();
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);

然后就可以使用了:

d3Service.ready.then(() => {
   //d3 can be used here 
});

另外,$timeout$scope.$apply 也不需要

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 2011-12-06
    • 1970-01-01
    • 2017-04-01
    • 2022-07-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    相关资源
    最近更新 更多