【问题标题】:Angular 2 / typescript pass service into promiseAngular 2 / typescript 将服务传递给承诺
【发布时间】:2019-03-06 00:50:19
【问题描述】:

如何将服务传递给承诺?我正在尝试创建一个承诺,该承诺将在所有 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();
                }
            });
        }
    });
}

【问题讨论】:

标签: angular typescript promise


【解决方案1】:

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

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

服务承诺

通常,组件根本不应该做出任何承诺。该服务为您的组件提供一个端点以访问业务逻辑和/或数据服务(数据库、外部 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。希望这会有所帮助!

【讨论】:

    【解决方案2】:

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

    这并不能直接回答你的问题,但我认为它会从你的 getter 中实现你想要的

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2018-10-01
      • 2015-08-12
      • 1970-01-01
      • 2017-02-21
      • 2017-03-01
      相关资源
      最近更新 更多