Angular2 - 在组件之间共享单件服务

时间:2016-08-30 08:46:19

标签: javascript angular

我正在尝试使用以下组件结构创建angular2应用程序:

应用

- mapView

虽然两个组件都应该引用包含第三方控件(esri map)的同一服务SimpleMapService

main.ts:

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './components/app.component';
import { SimpleMapService } from './services/map.service';

bootstrap(AppComponent, [SimpleMapService]);

app.component.ts:

import { Component, AfterViewInit } from '@angular/core';
import { SimpleMapService } from '../services/map.service';
import { MapViewComponent } from '../esri/map-view.component';


@Component({
    selector: 'myApp',
    templateUrl: '/app/components/app.component.html',
    directives: [MapViewComponent]

})
export class AppComponent implements AfterViewInit {            

    constructor(
        private _mapService: SimpleMapService
    ) {}

    ngAfterViewInit() {
       this._mapService.doSomethingWithTheService();
    }

}

地图view.component.ts:

import { Component, ElementRef, Output, EventEmitter } from '@angular/core';
import { SimpleMapService } from '../services/map.service';
import { Map, MapView } from 'esri-mods';

@Component({
    selector: 'map-view',
    template: '<div id="mapView"></div>'
})
export class MapViewComponent {
    @Output() viewCreated = new EventEmitter();

    view: any = null;

    public zoom = 10;

    constructor(
        private _mapService: SimpleMapService,
        private elRef: ElementRef
    ) {}

    ngOnInit() {
        this.view = new MapView({
            container: this.elRef.nativeElement.firstChild,
            map: this._mapService.map,
            zoom: 10,
            center: [19.937, 50.061],
            rotation: 0
        })

        this.view.then(function(view) {
            this.viewCreated.next(view);
        }.bind(this));

        this.view.watch('zoom', function(newVal, oldVal, propertyName) {
            this.zoom = newVal;
        }.bind(this));

    }

}

service.ts:

import { Injectable } from '@angular/core';
import { Map, FeatureLayer, GraphicsLayer } from 'esri-mods';

@Injectable()
export class SimpleMapService {
    map: any = null;

    public doSomethingWithTheService() : void {
        this.map.doSomething(); 

    }

    constructor() {
        this.map = new Map({
            basemap: 'streets'
        });

    }
}

我的问题: - MapViewComponent无法成功访问服务{/ 1}}:

  

platform-b​​rowser.umd.js:962 EXCEPTION:TypeError:无法读取属性   未定义的'doSomethingWithTheService'

我想我没有正确分享/处理服务?!

0 个答案:

没有答案