【发布时间】: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<d3>? -
或者,你试过this file?
-
嗨@Paarth,也许我做错了什么,但是当我只使用引用时,没有导入并说 ng.IPromise
,然后我收到错误“找不到名称 'd3 ’”。当我使用另一个文件时,我得到了同样的错误。 -
我应该澄清一下。当您尝试这样做时,您是否删除了
import *行但保留在/// <reference path行中?这是我的建议 -
是的,这确实给出了相同的结果。我在 d3.d.ts 文件中还看到它指示行 export = d3 为“duplicate identifier export ="
标签: angularjs d3.js typescript visual-studio-code typescript-typings