Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the constructor of the 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();
                }
            });
        }
    });
}

Answer №1

If you're struggling to access the this object within your Promise's executor function, check out this explanation for assistance (referenced by danh).

However, this structure may not be ideal for an Angular 2 app and could be causing issues. For guidance, refer to the official Angular 2 Style Guide, specifically the discussion on Components and Services.

Services and Promises

In general, Components should not handle Promises directly. Instead, a Service acts as a gateway to business logic and data services for Components to access.

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;
    }
}

Components and Promises

Components should interact with a service and consume the returned 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 proceed with your tasks.");
            })
            .catch(() => {
                console.log("Remember to handle any errors!");
            });
    });
}

Keep in mind:

  • Ensure Providers are set up correctly during bootstrap!
  • Adjust import paths accordingly.

I'm limited to two links, so explore more about Promises and Observables on the Angular 2 documentation site mentioned above. Hope this information is helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the x-api-key header with HttpInterceptor in Angular 4: A guide

I am attempting to use HttpInterceptor to set the header key and value, but I am encountering the following error: Failed to load https://example.com/api/agency: Response to preflight request doesn't pass access control check: No 'Access ...

Select dropdown menu with dynamic search feature

I need assistance with creating an editable mat select dropdown that fetches data from an API as an array of objects. I want the dropdown to have a filter autocomplete feature where if a user types 'R', it should filter out options starting with ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...

The specified format of `x-access-token` does not match the required type `AxiosRequestHeaders | undefined`

I am encountering an issue while trying to add an authHeader to the "Service". The error message displayed is: Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequest ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

What steps are involved in adding a table footer to ng2-smart-table?

I'm currently incorporating ng2-smart-table into my application. I am looking to include a table footer below the table to provide additional information such as Sum Amount, Discount Amount, and more. https://i.sstatic.net/SOTls.png Below is an examp ...

Ways to emit a value from an observable once it is defined?

Is it feasible to create an observable that can wrap around the sessionStorage.getItem('currentuser')? This way, calling code can subscribe and retrieve the value only after it has been set in the sessionStorage. Do you think this is achievable? ...

Steps to trigger a modal using an effect and automatically close it upon receiving a specific dispatched action

Is there a better way to handle the closing of a dialog after a specific action is dispatched? Currently, I have a CalendarEventDeleteDialog with "yes" and "no" options. If the user selects "yes," a CalendarEventDeleteAction is dispatched followed by a Cal ...

A Promise signature allows for the compilation of function bodies that return undefined

The compiler error that I expected to see when using this function does not actually occur. The function body is capable of returning undefined, yet the type signature does not mention this possibility. async function chat(_: at.ChatLine): Promise<Arr ...

Encountering a Typescript error when attempting to access the 'submitter' property on type 'Event' in order to retrieve a value in a |REACT| application

I am facing an issue with my React form that contains two submit buttons which need to hit different endpoints using Axios. When I attempt to retrieve the value of the form submitter (to determine which endpoint to target), I encounter an error while work ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

Creating Dynamic Forms in React with Typescript: A Step-by-Step Guide to Adding Form Elements with an onClick Event Handler

I am looking to create a dynamic generation of TextFields and then store their values in an array within the state. Here are my imports: import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button&apos ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

Beta 8 of Angular Material 2 is causing MdDialog.afterAllClosed to return an undefined result instead of the expected data

I am currently facing an issue where the result from the dialog component's close method is returning as undefined. Could this be a bug present in angular material 2 beta 8? I have searched extensively online but have not been able to find any inform ...

Looking for help with setting up Nodemailer and installing it via NPM

I am currently developing a mobile application using Ionic with Angular/Typescript, and I'm in need of a front-end solution to dynamically send emails in the background to a specific email address. I tried using emailjs, but it requires JavaScript whi ...

Iterate through each item in an object using Angular

I attempted to utilize a forEach loop, but it's indicating that it's undefined for some reason. Here is my code snippet: var array: MoneyDTO[] = prices array.forEach(function (money: MoneyDTO) { if (money.currency == 'QTW& ...

Determining the best method for change detection in Angular 2: Choosing between Observable, EventEmitter, and Dot Rule

Managing change detection in Angular2 can be approached in three different methods that I have observed. Utilizing Observables @Injectable() export class TodosService { todos$: Observable<Array<Todo>>; private _todosObserver: any; ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...

Resolving the non-null assertion error in TypeScript and React: A step-by-step guide

My code snippet is as follows: type ItemProps = { status?: string; } <Items status={status!} /> // encountering an error with a warning about forbidden non-null assertion // @typescript-eslint/no-non- ...