Promise in Angular2 using TypeScript

Would like to implement a generic HTTP GET service, and I have achieved it using the code snippet below:

public get(module: String): Promise<any> { 
return this.http.get(module)
           .toPromise()
           .then(response => response.json().data as Any[])
           .catch(this.handleError);}

However, I am facing an issue where I want to execute a command once the HTTP GET request is completed, but I am unsure how to accomplish this.

Adding something to the .then step does not yield the desired result:

.then(response => response.json().data as Any[] && alert("HI"))

Alternatively, adding another .then after the initial one causes the command to fire before the HTTP request is fully processed.

What would be the best approach to achieve this?

When utilizing the dfsq code, I am able to successfully trigger alert("HI"), however, the response returned is undefined. Here is an example of how I am using it:

this.dataService.get("myurl").then(response => console.log(response));

Unfortunately, the output is undefined.

Answer №1

It is essential to include an additional then block in your code:

public fetch(content: string): Promise<any> { 
  return this.http.get(content)
           .toPromise()
           .then(result => result.json().data as Any[])
           .then(response => {
             console.log("HELLO") // <---- perform an action at this point
             return response
           })
           .catch(this.handleError);
}

Ensure that you return the previous response from the preceding then block to maintain the flow in the promise chain.

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

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

What could be the reason for the failed authentication HTTP request to Firebase resulting in error 400?

Ensuring the correctness of the API: ''' https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY] ''' source Verifying my API Key: https://i.sstatic.net/N4daZ.png The request made from a component: import { In ...

Unable to utilize ngForm when values are already predefined

I have an Angular application with Ionic 4. Here is the HTML code for my form: <form #formAuth="ngForm" (ngSubmit)="sendCode(formAuth)" method="post"> <ion-select placeholder="Country" ngModel name="area_code" interface="modal"> <io ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Ideal method of re-entering ngZone following an EventEmitter event

There is a specific component that wraps around a library, and to prevent the chaos of change detection caused by event listeners in this library, the library is kept outside the Angular zone: @Component({ ... }) export class TestComponent { @Output() ...

Guide to integrating an Angular 6/7 project as a dynamic plugin within a separate Angular 6/7 project

Currently embarking on a new project in Angular 7, however facing the challenge of incorporating 6 to 8 existing projects into this new platform dynamically as plugins. Your input on the feasibility and thoughts about this strategy would be greatly appreci ...

Best practices for stubbing an element in order to effectively unit test a LitElement component

Trying to perform unit tests on LitElement components has been quite a challenge for me. I found myself stuck when attempting to isolate components, particularly in figuring out how to stub elements effectively. The Polymer project provides some informatio ...

eliminate any redundant use of generics

Recently, I attempted to create a pull request on GitHub by adding generics to a method call. This method passes the generically typed data to an interface that determines the return type of its methods. However, the linter started flagging an issue: ERR ...

Converting a promise of type <any> to a promise of type <entity>: A beginner's guide

As a newcomer to TypeScript and NestJS, I am wondering how to convert Promise<any[]> to Promise<MyEntity[]> in order to successfully execute the following code: const usersfromTransaction = this.repoTransaction .createQueryBuilder() ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Mastering Typescript lookup types - effectively limit the properties included in a merge operation with the Partial type

Exploring lookup types, I'm interested in creating a safe-merge utility function that can update an entity of type T with a subset of keys from another object. The objective is to leverage the TypeScript compiler to catch any misspelled properties or ...

Utilize nested JSON Response as row data for ag-Grid in Angular 4

Just starting out with angular and working on a project where I need to display JSON data in a grid. I've opted for ag-grid. Here's the sample JSON response I'm receiving from a rest API: [ { "id": 64, "name": "Utopia", "language": ...

trouble with the layout of the table

Could you assist me in improving the design to enhance data clarity? Your help would be greatly appreciated. Thank you for your anticipated response. CSS File: table-layout: fixed; width: 100%; border-collapse: collapse; table-layout: fixed; ove ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Verifying TypeScript errors before each commit in a Vue application

We have set up a git hook in our app using Husky for pre-commit actions. Whenever someone commits code, it triggers the pre-commit code - #!/bin/sh . "$(dirname "$0")/_/husky.sh" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_ ...

How to access a component attribute in a JavaScript library method in Angular 8

Within my Angular project, I am utilizing Semantic UI with the code snippet below: componentProperty: boolean = false; ngOnInit() { (<any>$('.ui.dropdown')).dropdown(); (<any>$('.ui.input')).popup({ ...

The 'ngModel' property cannot be bound to a 'textarea' element because it is not recognized as a valid property

When I run Karma with Jasmine tests, I encounter the following error message: The issue is that 'ngModel' cannot be bound since it is not recognized as a property of 'textarea'. Even though I have imported FormsModule into my app.modu ...

Creating a singular and distinctive string by combining two keywords

Is it possible to create a single distinct string by combining two keywords regardless of the order in which they are entered? EDIT: The keywords in question are numerical rather than alphabetical characters. The following example is merely for explanator ...