2016-11-28 29 views
1

我正在尝试使用TypeScript为我的Angular 2组件提供服务。我阅读了很多关于如何创建服务的教程,并且他们都说我的服务需要使用装饰器@Injectable,并且我应该能够将其注入到组件中。当我想注入我的服务时,这似乎不适用于我,但使用@Inject。Angular 2 @Injectable似乎没有工作

我的服务:

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)) 
    } 
} 

你能请向我解释为什么只有第二个版本有效?

+1

定义“不工作”。究竟发生了什么?你可以在plunkr中重现吗? –

+1

可能你的问题非常类似于http://stackoverflow.com/questions/39602890/angularjs-2-0-cant-inject-anything-through-component-constructor – yurzui

+0

将它添加到你的模块 – chabeee

回答

0

我发现在我的tsconfig.json中缺少“emitDecoratorMetadata”。我把它与“emitDecoratorData”混淆了。感谢您的帮助!

0

@Inject()是一种告诉Angular必须注入参数的手动方式。建议不要以您使用它的方式使用它。

对于第一个例子,我认为你没有告诉你的应用程序模块你正在使用该注射器。您必须将其导入您的主应用程序模块,并将其作为provider使用。然后你就可以将它注入到其他组件中,正如你所说的依赖注入器,GeolocationService类现在可以注入到其他类中。