2016-11-28 11 views
1

私は、角型2型のサービスをTypeScriptで作成しようとしています。私はサービスの作成方法に関するチュートリアルをたくさん読んでいましたが、私のサービスではデコレータ@Injectableを使用する必要があり、コンポーネントに注入できるだけで済むようになっています。これは私のサービスを注入したいときに私のために働いているようには見えませんが、@Injectを使用すると役に立ちます。 角2 @注入可能でないようです。

マイサービス:

import { Injectable } from '@angular/core'; 
    import { Observable } from 'rxjs'; 

    @Injectable() 
    export class GeolocationService { 

    /** 
    * Get the current location of the user 
    * @return {Observable<any>} An observable with the location of the user. 
    */ 
    public getLocation(): Observable<any> { 
     return Observable.create(observer => { 
      if (window.navigator && window.navigator.geolocation) { 
       window.navigator.geolocation.getCurrentPosition(position => { 
        observer.next(position); 
        observer.complete(); 
       }, error => { 
        observer.error(error); 
       }, { 
        maximumAge: 0 
       }); 
      } else { 
       observer.error('Browser does not support location services'); 
      } 
     }); 
    } 
} 

私のコンポーネント、機能していないバージョン(V1):

import { GeolocationService } from './geolocation.service'; 

@Component({ 
    templateUrl: 'home.component.html', 
    styleUrls: [ 'home.component.scss' ], 
    providers: [ GeolocationService ] 
}) 
export class HomeComponent implements OnInit { 

    constructor(private myService: GeolocationService) { 
     this.myService.getLocation() 
      .subscribe(position => console.log('my position', position)); 
      // .error(err => console.log('oop error', err)) 
    } 
} 

マイ部品、作業バージョン(V2)

import { GeolocationService } from './geolocation.service'; 

@Component({ 
    templateUrl: 'home.component.html', 
    styleUrls: [ 'home.component.scss' ], 
    providers: [ GeolocationService ] 
}) 
export class HomeComponent implements OnInit { 

    constructor(@Inject(GeolocationService) private myService: GeolocationService) { 
     this.myService.getLocation() 
      .subscribe(position => console.log('my position', position)); 
      // .error(err => console.log('oop error', err)) 
    } 
} 

することができますなぜ2番目のバージョンだけが動作するのかを私に説明してください。

+1

「機能していません」と定義します。正確にはどうなりますか?あなたはそれをplunkrで再現できますか? –

+1

あなたの質問は、http://stackoverflow.com/questions/39602890/angularjs-2-0-cant-inject-anything-through-component-constructorに非常によく似ています – yurzui

+0

あなたのモジュールにそれを追加してください – chabeee

答えて

0

"emitDecoratorMetadata"がtsconfig.jsonにないことがわかりました。私はそれを "emitDecoratorData"と混同しました。あなたの助けを借りてありがとう!

0

@Inject()は、Angularにパラメータを注入する必要があることを手動で伝える方法です。使用中の方法で使用することはお勧めしません。

最初の例では、あなたがあなたのアプリケーションモジュールにあなたがその注射可能物を使用しているとは言わなかったと思います。メインアプリケーションモジュールにインポートしてproviderとして使用する必要があります。それで、GeolocationServiceクラスを他のクラスに注入できる依存性注射器に言ったように、それを他のコンポーネントに注入することができます。