Unable to attach API data to client variable in Angular 6

I am encountering a challenge with binding requested API data to a variable in my component.

Firstly, here is my server-side method (using Express and Mongoose).

    app.post('/api/rolloutMeeting', async (req, res)=> {
    var singleMeetingID = req.body
    singleMeetingID = singleMeetingID.singleMeetingID
    var meeting = []

    meeting[0] = await Meeting.findOne({_id: singleMeetingID})
    companyID = meeting[0].compID.compID

    meeting[1] = []
    for(var i = 0; i < meeting[0].projectIDs.length+1; i++) {
        meeting[1][i] = await Project.findOne({_id: meeting[0].projectIDs[i]})
    }

    meeting[2] = []
    for(var j = 0; j < meeting[1][j].taskIDs.length; j++) {
        for(var k = 0; k < meeting[1][j].taskIDs.length; k++) {
            meeting[2][j] = await Content.findOne({_id: meeting[1][j].taskIDs[j]})
        }
    }

    console.log(meeting)

    res.json(meeting)
})

The output is exactly as desired and working fine.

This is my Service Method that requests the data from the API.

  rolloutMeeting(singleMeetingID) {
    return this.http.post('/api/rolloutMeeting', {
      singleMeetingID
    })
  }

Lastly, my component where the mistake might be hiding:

      import { Component, OnInit, Input } from '@angular/core';
import { MeetingService } from '../../meeting.service';
import { ProjectService } from '../../project.service';
import { ContentService } from '../../content.service'
import { meeting } from '../../meeting'
import { project } from '../../project';

@Component({
  selector: 'app-singlemeeting',
  templateUrl: './singlemeeting.component.html',
  styleUrls: ['./singlemeeting.component.css']
})
export class SinglemeetingComponent implements OnInit {
  @Input() singleMeetingID: String;

  constructor(private meetServ: MeetingService,
    private proServ: ProjectService,
    private taskServ: ContentService) { }

  ngOnInit() {
    this.getData()
  }

  getData() {
    this.meetServ.rolloutMeeting(this.singleMeetingID)
      .subscribe(data => this.meeting : any = data)
    console.log(this.meeting)
  }

  tasks = []
  projects = []
  meeting : any
}

Upon doing this: .subscribe(data => console.log(data)), I receive the exact output as when I log the meeting array on my server.

I have tried various methods to bind it to my meeting Array in the Client like:

.subscribe(data => this.meeting = data[0] as meeting)

and

.subscribe(data => this.meeting = data as meeting)

and

    .subscribe(data => function {
    this.meeting = data
})

For each attempt, I initialized the meeting var as any, an array, and without any declaration.

However, none of those attempts seemed to work for me. Console.log(this.meeting) always gives me undefined, while console.log(data) always returns the answer I actually want.

My goal is to put data[0] into a meeting variable and run my meeting interface over it, data[1] into project Array with the project interface, and so on...

Thank you to anyone who reads this and tries to help.

Best Regards

Answer №1

The definition of the meeting type and controller class are not displayed, but you can try this:

.subscribe(data => { this.meeting = data; console.log(this.meeting) } )

The issue with the console.log displaying undefined is because the callback function inside subscribe is executed asynchronously (AFTER the next line of code: console.log). Therefore, if you place console.log inside the callback, you will see the result.

You could also utilize the following code snippet using async/await:

async getData() {
    this.meeting = await this.meetServ.rolloutMeeting(this.singleMeetingID).toPromise();
    console.log(this.meeting)
}

However, it's important to note that the code after await (like console.log) will be executed asynchronously after the data has been loaded. This syntax helps make your asynchronous code look synchronous, reducing nesting levels.

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

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

How does the order of objects in an array change when using *ngFor in Angular with a .subscribe() method in Ionic 3?

As a newcomer to Ionic 3 & Angular, I encountered a challenge with the *ngFor and .subscribe() method. Please bear with me if this question seems simple. I attempted to understand the behavior of the http.get(..).map(..).subscribe() function when combined ...

Having trouble understanding how to receive a response from an AJAX request

Here is the code that I am having an issue with: render() { var urlstr : string = 'http://localhost:8081/dashboard2/sustain-master/resources/data/search_energy_performance_by_region.php'; urlstr = urlstr + "?division=sdsdfdsf"; urlst ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

What are some best practices for implementing pagination using Angular Material?

While following a tutorial by Muhi Masri on how to implement an Editable Dynamic Table using Angular Material Paginator (the tutorial can be found here, highly recommended), I encountered an issue where the paginator was not working as expected. Despite fo ...

Using React to iterate over an array of objects and generate Date TextFields in Material UI

I have an array of objects representing different stages in a specific process, each stage identified by an id and name. The structure of the array is as follows: const stages = [ { id: 1, name: initialize }, { id: 2, name: execute ...

What is the best way to store relational data in mongoose?

What is the best way to store relational data in mongoose? Should I nest them within each other? For instance, let's say I have a schema for saving restaurants. Each user can provide feedback on a restaurant and then I need to calculate and display ...

Using AngularFire2 to manage your data services?

After diving into the resources provided by Angular.io and the Git Docs for AngularFire2, I decided to experiment with a more efficient approach. It seems that creating a service is recommended when working with the same data across different components in ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Exploring the attributes of optional features

Dealing with optional properties can be quite tedious. Consider the object test1 in TypeScript: interface Test { a?: { b?: { c?: { d?: string } } }; } const test1: Test = { a: { b: { c: { d: 'e' } } } }; Handling the absence of each proper ...

When using Mongoose's findByIdAndUpdate method, it does not provide an error message if the specified Id cannot be found

I am currently working on a RESTful API to update mongo DB data. However, I have encountered an issue where the findByIdAndUpdate method does not throw an error when an ID that is not present in the database is passed as input. Instead, it simply returns a ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

Dealing with timing errors in React when making a POST request

My current setup involves a React file connected to an Express/Node backend and SQL database. The backend functionalities are working as expected, with all routes tested and verified using Postman. The application can successfully handle GET, POST, UPDATE, ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

Ways to keep backend and frontend separate within Docker using Nuxt

I'm planning to divide my Nuxt app and dockerize the backend and frontend paths in separate folders. The structure of the project will have: my_nuxt_app |-backend |-frontend docker-compose.yaml Locally, this setup works fine with the foll ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...

What is the best way to divide middleware within feathers?

I have been using the multer library with feathers to upload files. In my effort to separate logic from code, I have decided to move the upload functionality from the index.js file to a new file named pdf.js within the middleware directory. Below is the c ...

Angular 2: Combining objects from various classes that extend a superclass into a single array

In my Angular 2-Native Script app, I am working on creating a service that manages an array of news items with different types such as Big, Small, Referral, each having unique parameters. The service will include various methods to manipulate this data. B ...

Error Message: Unable to access 'map' property of undefined in TSX file

Component for displaying attendees in an activity interface IProps { attendees: IAttendee[] } export const ActivityListItemAttendees: React.FC<IProps> = ({attendees}) => { return ( <List horizontal> {attendees.ma ...