如何在Angular 2/4中的异步方法中设置服务的属性

时间:2017-07-06 16:27:37

标签: angular asynchronous

我有一个服务和组件如下:

import {OnDestroy, Component} from '@angular/core';
import { JumpService } from "./jump-service";
@Component({
  selector: 'jumper',
  providers: [JumpService]
})
export class Jump implements OnDestroy {
   constructor(
        private _jumpService: JumpService
    ) {

    }
private async _JumpAndShoot(): Promise<area51.armor> {
        let oxy = await this._panic;
        if (!oxy) return;
        this._jumpService.armour = { a, b };
        this._jumpService.oxy = oxy;
        return { a, b };
    }
}

服务:

import { Injectable } from "@angular/core";
@Injectable()
export class JumpService {

     armor: area51.armor;
     oxy: area51.oxylevel;

shoot() {
 //logic
 console.log("Value of oxy", this.oxy); // shows undefined.
}

}

尽管oxy的值是在异步方法内的JumpService上设置的,但当我尝试访问时,它在我的服务中始终显示为undefined。而我在访问方法中设置的装甲属性时没有问题。在处理async方法时,是否有任何不同的设置属性的方法?请帮忙。

谢谢。

1 个答案:

答案 0 :(得分:2)

如果您在@Component(providers: [JumpService])等组件中使用提供程序,则该组件及其树将是本地提供程序。在主模块或顶级组件中提供它。