Type void does not have a property of type forEach

I've encountered similar questions before, such as this one: (forEach Typescript TS2339 "does not exist on type 'void'")

Despite that, I'm still struggling to solve my specific issue.

ngOnInit() {

      var __this = this;

      this.historianService.getHistorian()
      .then(function(res){
          console.log(res)

          res.forEach(transaction => {
              __this.results.push(res);

          })
  })
 }

The output of console.log(res) is:

    (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
0
:
{$class: "org.hyperledger.composer.system.HistorianRecord", transactionId: "1dec5c91d047deebb588d69e4844ccdda03b3621783bc6c8c82b286e6e4c3d65", transactionType: "org.hyperledger.composer.system.IssueIdentity", transactionInvoked: "resource:org.hyperledger.composer.system.IssueIden…bb588d69e4844ccdda03b3621783bc6c8c82b286e6e4c3d65", participantInvoking: "resource:org.hyperledger.composer.system.NetworkAdmin#admin", …}
1
:
{$class: "org.hyperledger.composer.system.HistorianRecord", transactionId: "2114019f-7179-4f0f-b0fc-bc25d116f2eb", transactionType: "org.hyperledger.composer.system.ActivateCurrentIdentity", transactionInvoked: "resource:org.hyperledger.composer.system.ActivateC…rentIdentity#2114019f-7179-4f0f-b0fc-bc25d116f2eb", identityUsed: "resource:org.hyperledger.composer.system.Identity#…f1adb8973507f6c7316039a49d92ab007abccf3a882b7dad3", …}
2
:
...
length
:
7
__proto__
:
Array(0)
...

Although the returned variable res has the forEach function associated with it, I am unable to use it as expected:

res.forEach(transaction => {
          __this.results.push(res);
      })

This results in an error message:

Property 'forEach' does not exist on type 'void | Response'. Property forEach does not exist on type 'void'

EDIT: Definition of getHistorian function:

 getHistorian(){

    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    var __this = this;
    return this.http.get('http://'+ this.ip +':3000/api/system/historian?access_token=' + this.access_token,options)
    .toPromise()
    .then(function(res){
        res = res.json();
        return res;
    })
    .catch(e => {console.log(e); //print error if there is one
    });

Answer №1

It seems like the issue could be due to having a return statement inside the ngOnInit function.

To fix this, you should update your code as follows:

this.historianService.getHistorian() // remove the return statement here since it's called inside ngOnInit
    .then((res) => { // use fat arrow function instead of regular function
        console.log(res);
        res.forEach(transaction => {
            this.results.push(res);
        });
})

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

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

Implementing strong security measures for Angular and .Net Core APIs using Azure AD authentication and defining specific application roles

My system is a combination of Angular front end and .Net Core API back end. Both are set up as distinct Active Directory apps in the Azure Portal. As a result, both applications are protected by Azure AD. The API is exposed and interacted with by authenti ...

What is the process for importing a map from an external JSON file?

I have a JSON file with the following configuration data: { "config1": { //this is like a map "a": [ "string1", "string2"], "b": [ "string1", "string2"] } } Previously, before transitioning to TypeScript, the code below worked: import ...

After version 3.1, TypeScript no longer supports callback functions as argument types

I've encountered an issue with jQuery Terminal. My d.ts file is quite large, but it's not functioning correctly. I attempted to update dependencies, leading to everything breaking. Recently, I've been unable to update TypeScript due to error ...

"Utilizing Angular's RxJS to efficiently filter an observable

I am currently attempting to filter a stream of products using an array of filters, but I am unsure of the best approach. Let me clarify my goal: I want to store the filtered result in the variable filteredProducts. To perform the filtering, I need to ite ...

Slim and Angular2 htaccess configuration

I am encountering an issue with my htaccess file and could use some assistance. My setup includes an Angular2 app (single page client side app, index.html) and a slim-v3 PHP REST API (index.php). The Angular2 app interacts with the REST API, and I would id ...

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...

Utilizing AngularJS2 with PHP on Apache server

Starting my journey with AngularJS today. Following tutorials on AngularJS version 2 using JavaScript. Node.js is a requirement, but my current development environment includes PHP, MySQL, and Apache (Xampp). I am curious if it is possible to develop and ...

Issues arise with file compilation in Angular 5

I want to apologize in advance for my English. I am encountering a problem when running `ng build --prod` on my Angular project. The following errors are being returned: ERROR in Error: Error: Internal error: unknown identifier undefined at Object. ...

The Angular HttpErrorResponse is a class used for handling

I am encountering an issue while attempting to retrieve a user's cart by submitting the username in the request URL. list: PanieDto[] = []; @Input() listform: PanieDto = new PanieDto(); isLoggedIn = false; showAdminBoard = false; showModeratorBoard = ...

Tips for including a clickable button in an Angular textarea

I am looking for a solution to float a button to the top right corner of a text area in an Angular application. Below is my current code setup, but unfortunately, it does not achieve the desired result: <textarea matInput matInput rows="15" cols="40" ...

Server-side props become inaccessible on the client side due to middleware usage

I'm attempting to implement a redirect on each page based on a specific condition using Next.js middleware. Strange enough, when the matcher in middleware.ts matches a page, all props retrieved from getServerSideProps for that page end up being undef ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

What is a different approach in Angular that can be used instead of the href attribute found in

I am trying to define a constant URL in my component.ts file so that I can test it and use it in my HTML file. I have tried using ngHref but it's not working in my case. How can I successfully define a constant URL in my component.ts file and access i ...

Sequelize's bulk synchronization process is ineffective

I am facing an issue with getting sequelize.sync() to function properly. When I call sync() for each model definition individually, it works perfectly fine. However, when trying to execute it from the sequelize instance itself, it seems like the registered ...

An issue has occurred: The function _co.collapsed is not of type function

Within my HTML template, I am utilizing the ngFor directive as shown below: <div class="card" *ngFor="let item of mydataarray"> <div class="card-header" (click)="item.isCollapsed = !item.isCollapsed"> <div class="card-body" [collapse]="ite ...

Encountering issue with ngIf directive in Angular

In my Angular project, I am trying to display data from a variable that is formatted in json. I have successfully done this using *ngfor, but now I also want to add a condition where it checks if msg.who=="Bot". My current code looks like this: <div cl ...

Issue with installing angular CLI on Windows 10

Having trouble installing Angular CLI with npm on a Windows 10 system I've exhausted all possible solutions Attempted clearing the cache and re-running the installation command - npm install -g @angular/cli - but encountered new errors every tim ...

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

Efficient access to variable-enumerated objects in TypeScript

Let's say I have the following basic interfaces in my project: interface X {}; interface Y {}; interface Data { x: X[]; y: Y[]; } And also this function: function fetchData<S extends keyof Data>(type: S): Data[S] { return data[type]; } ...