如何在经典HTML5和Angular2应用程序之间共享typescript classe?

时间:2017-03-23 14:44:12

标签: javascript html5 angular typescript cross-platform

我们有一些传统的常规HTML5应用程序使用我们自己的dataviz模块(基于d3.js的javascript库)。

我们开始在angluar2上用typescript编写一个新的应用程序,它也需要包含相同的dataviz组件。

我已经将dataviz模块重写为打字稿中的全新lib,它基于适应angular2应用程序的反应。通过更好地集中通用代码并使Web服务成为基于新的Web服务打字稿类的角度服务,我已经利用重写机会更好地构建了dataviz模块。

我现在面临的问题是,我有两个不同的语言(和技术支持)编写的dataviz模块相同,这种情况迫使我们维护两个不同的源代码。

换句话说,是否可以将打字稿版本注入旧版HTML5 / javascript应用程序?

到目前为止,我想我可以使用生成的javascript angular2将打字稿语言直接包含在遗留应用程序中。

但是如何处理angular2装饰命令,如@ Injectable,@ Component,@ ViewChild等。和进口?

例如,当我包含以下打字稿的js生成文件时,我收到错误TypeError:undefined不是一个对象(评估' core_1.ViewChild'),它出现在这里:

   }; // drawChartTraffic(force)
    __decorate([
        core_1.ViewChild('chart'), 
        __metadata('design:type', core_1.ElementRef)
    ], DatavizComponent.prototype, "chartContainer", void 0);
    __decorate([
        core_1.Input(), 
        __metadata('design:type', String)
    ], DatavizComponent.prototype, "graphId", void 0);

我的理解是我应该包含angular2 / core和所有使用的libs,这没有任何意义,因为我想要实现的是简单...

我应该转向包含Dataviz的iframe吗?有什么想法吗?

打字稿摘录:

import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import * as d3 from 'd3';
import { Observable }           from 'rxjs/Observable';
import { ZEENSMetricsService }  from './zeensmetrics.service'


@Component({
    selector:    'dataviz-offers-volumes',
    templateUrl: 'app/dataviz.component.html',
    styleUrls:  ['app/dataviz.component.css'],
    encapsulation: ViewEncapsulation.None,
    providers: [
        {provide: 'wsAuthKey',  useValue: 'abc'}, 
        {provide: 'wsHost',     useValue: 'efg'}, 
    ],
})
export class DatavizComponent implements OnInit, OnChanges {

    @ViewChild('chart') private chartContainer: ElementRef;
    @Input() private graphId:string;
    @Input() private wsAuthKey:string;
    @Input() private wsHost:string;
    @Input() private maxSamples=12;

    private graph: any;     // chartContainer native element

    // …
}

1 个答案:

答案 0 :(得分:0)

由于您的DatavizComponent是Angular 2组件,因此如果不包含整个Angular 2框架,则无法将其包含在旧版应用程序中。

所以,我认为您应该将核心Dataviz模块拆分为与框架无关的库。在此lib中放入所有不依赖于Angular的代码。导入此库并将其封装在Angular组件中。

import {template, styles, Dataviz} from 'my-dataviz-lib';

@Component({
    selector: 'dataviz-offers-volumes',
    template: template,
    styles: styles,
    //...
})
export class DatavizComponent implements OnInit, OnChanges {

    private viz: Dataviz; // Your library object

    // …
}