私は、角型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番目のバージョンだけが動作するのかを私に説明してください。
「機能していません」と定義します。正確にはどうなりますか?あなたはそれをplunkrで再現できますか? –
あなたの質問は、http://stackoverflow.com/questions/39602890/angularjs-2-0-cant-inject-anything-through-component-constructorに非常によく似ています – yurzui
あなたのモジュールにそれを追加してください – chabeee