将值从服务传递到组件(Angular2)

时间:2016-12-21 21:01:04

标签: angular angular2-services

我有服务:

@Inject()    
export class MyService{
...
    // this.status has a value which I can print in the console.
    //Now let's write a function to call it from my component

getGood(): any{
        return this.status;
    }
}

现在,在我的组件中:

export class MyComponent {

    statusFromServer: number;

    constructor(private router: Router, @Inject(UploadedFile) private _uploadedFile: UploadedFile){
    }    
    .....    
    handleUpload(): void {

        this.statusFromServer = this._uploadedFile.getGood();
        console.log(this.statusFromServer);   
    }         
}

我该怎么做才能得到这个。可以在组件中访问和打印状态?我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

@Inject()    
export class MyService{

应该是

@Injectable()    
export class MyService{
constructor(private router: Router, @Inject(UploadedFile) private _uploadedFile: UploadedFile){

应该是

constructor(private router: Router, private _uploadedFile: UploadedFile){

如果这没有帮助,我认为MyService.status是由某些异步调用设置的,而在执行this.statusFromServer = this._uploadedFile.getGood();时尚未提供。

答案 1 :(得分:0)

尝试以下,

get handleUpload(): void {
   return this._uploadedFile.getGood();  
}  

希望这会有所帮助!!

相关问题