Angular 2 / typescript将服务转化为承诺

时间:2016-09-07 22:06:11

标签: angular typescript promise

如何将服务传递给承诺?我正在尝试创建一个将在所有http请求返回时解决的承诺。现在this.jiraService未定义。无论如何将它传递给promise的构造函数?

export class JiraComponent {
private stories:Map<string,number> = new Map<string,number>();

constructor(private jiraService:JiraService) {
}

ngOnInit() {
    this.jiraService.search()
        .then(x => this.getKeys(x['issues']))
        .then(keys => this.getLogs(keys))
        .then(x => console.log(this.stories));
}

getKeys(issues:Array<Object>) {
    let keys = new Array<string>();
    for (var i of issues) {
        keys.push(i['key']);
    }
    return keys;
}

getLogs(keys:Array<string>) {
    return new Promise(function (resolve, reject) {
        let count = 0;
        for (var k of keys) {
            this.jiraService.worklog(keys[0]).then(x => {
                count++;
                console.log(x);
                if (!this.stories.get(k)) {
                    this.stories.set(k, x['timeSpentSeconds']);
                }
                else {
                    this.stories.set(k, this.stories.get(k) + x['timeSpentSeconds']);
                }
                if (count == keys.length) {
                    resolve();
                }
            });
        }
    });
}

2 个答案:

答案 0 :(得分:1)

如果您在Promise的执行程序函数中访问this对象时遇到问题,this explanation可能会帮助您(上面提到danh)。

然而,这不是Angular 2应用程序的规范结构,这可能是您的一些麻烦的根源。一个好的起点是官方Angular 2 Style Guide关于组件和服务的讨论(尽管这些都值得一读!)。

服务承诺

通常,组件不应该做任何Promise。该服务为您的组件提供了一个端点,用于访问业务逻辑和/或数据服务(数据库,外部API等)。

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

@Injectable()
export class MyService {
    private allIsGood: boolean;

    public doSomething(): Promise<any> {
        console.log("I promise to return at some point.");
        return new Promise(function (resolve, reject) {
            this.allIsGood = someLongRunningActivity();
            if (this.allIsGood) {
                console.log("Resolving the promise.");
                resolve();
            } else {
                console.log("Something bad happened, don't forget to check for errors!");
                reject();
            }
        });
    }

    private someLongRunningActivity(): boolean {
        //run a query or perform some calculation
        return true;
    }
}

组件获得承诺

组件应该调用服务并使用它返回的Promise。

import { Component } from '@angular/core';
import { MyService } from '../services';

@Component({
    selector: 'my-selector',
    templateUrl: 'my template.html'
})
export class MyComponent {

    constructor(private myService: MyService) {
        this.myService.doSomething()
            .then(() => {
                console.log("The promise was honored, you can do what you were waiting to do.");
            })
            .catch(() => {
                console.log("You remembered to check for errors!");
            });
    });
}

一些警告:

  • 这假设您在初始引导过程中正确设置了提供程序!
  • 您的导入路径可能会有所不同......

我只允许发布两个链接,所以我无法提供更多好的参考资料。从上面阅读Angular 2文档站点上的Promises和Observables。希望这有帮助!

答案 1 :(得分:0)

使用Promise.All([p1, p2, p3]) - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

怎么样?

这不会直接回答你的问题,但我认为它会从你的getter中获得你想要的东西