Angular2启动时的Instanciate服务

时间:2017-01-12 13:51:20

标签: angular

我有一个(单例)服务,它包含构造函数中的一些代码,这些代码应该在启动后直接运行。当应用程序加载时,必须立即创建一个实例。

实现服务的一种可能性是将其放在app组件的构造函数中:

var source = new ol.source.Vector();

var styleFunction = function (feature) {
    var geometry = feature.getGeometry();
    var styles = [
        // linestring
        new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            })
        })
    ];

    geometry.forEachSegment(function (start, end) {
        var dx = end[0] - start[0];
        var dy = end[1] - start[1];
        var rotation = Math.atan2(dy, dx);

        var lineStr1 = new ol.geom.LineString([end, [end[0] - 200000, end[1] + 200000]]);
        lineStr1.rotate(rotation, end);
        var lineStr2 = new ol.geom.LineString([end, [end[0] - 200000, end[1] - 200000]]);
        lineStr2.rotate(rotation, end);

        var stroke = new ol.style.Stroke({
            color: 'green',
            width: 1
        });

        styles.push(new ol.style.Style({
            geometry: lineStr1,
            stroke: stroke
        }));
        styles.push(new ol.style.Style({
            geometry: lineStr2,
            stroke: stroke
        }));
    });

    return styles;
};

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        new ol.layer.Vector({
            source: source,
            style: styleFunction
        })
    ],
    target: 'map',
    view: new ol.View({
        center: [0, 0],
        zoom: 3
    })
});

map.addInteraction(new ol.interaction.Draw({
    source: source,
    type: ('LineString')
}));

但由于我从未在此组件中使用myService,因此我会收到<script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script> <link href="https://openlayers.org/en/v3.20.1/css/ol.css" rel="stylesheet"/> <div id="map" class="map" tabindex="0"></div>之类的警告,并且我团队中的其他人可能会删除该服务。有没有办法在app模块中实现服务?

2 个答案:

答案 0 :(得分:4)

您可以提供虚拟APP_INITIALIZER并将其作为dependency传递给

@NgModule({
  providers: [{provide: APP_INITIALIZER, useMulti: true, deps: [MyService], useFactory: (myService) => null}]

答案 1 :(得分:-1)

当你将服务放在 NgModule声明中意味着你从那里实例化服务......

使用此语法时:

constructor(private mySercive: MyService
打字稿中的

只是告诉编译器 TYPECASTING 它对服务没有任何作用....

要检查是否真的与它只是打字稿相关的东西...... 从构造函数中删除它并使用相同的类型转换创建变量...

像这样

class ComponentClass {
    mySercive: MyService;
}