Tips for extracting a property from an object that is returned by a method

I'm having trouble assigning the value "contact.company_name" from the getClient method.

  getContacts() {
    this.contactService.getContacts().subscribe(
      data => {
        for (let contact of data) {
          contact.company_name = this.getClient(contact);
          console.log(contact);
        }
        this.contacts = data
      },
      error => console.log(error),
      () => this.isLoading = false
    );
  }

The response returned by the http-request in this.getClient(contact) is:

{_id: "59f43f1a3a2fc421c00ad8b1", name: "company2", street: "street 2", zipcode: "45678",…}

How can I ensure that contact.company_name matches company.name? The ids in contact.company and company._id are the same. The http-request and response seem to be correct.

For example, a sample contact object may look like this:

{
anrede : "sir"
company : "59f43f1a3a2fc421c00ad8b1"
nachname :"surname1"
titel : "dr."
vorname : "name1"
__v : 0
_id : "59f43f363a2fc421c00ad8b2"   
}

Answer №1

To ensure that the company always exists, simply include .name at the end of the line:

contact.company_name = this.getClient(contact).name;

If there is a possibility that it may not exist, it's important to check for its presence first:

const company = this.getClient(contact);

if (company) {
    contact.company_name = company.name;
}

UPDATE

After understanding how your getClient method functions, it seems that while you mentioned it returns a JavaScript object, it actually doesn't return anything and instead subscribes to an observable.

Here is one approach to resolve this using forkJoin (you may need to import this operator to utilize it):

getContacts() {
  return this.contactService.getContacts()
    .flatMap(data => {
      if (data.length > 0) {
        return Observable.forkJoin(
          data.map(contact => {
            return this.contactService.getClient(contact)
              .map(company => {
                contact.company_name = company.name;
                console.log(contact);

                return contact;
              });
          }));
      }

      return Observable.of([]);
    });
}

For further examples on combining observables, refer to the following article:

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

Display the div element only if the router is active and the navbar is visible

I am attempting to display a div underneath each link in a navbar when the page is active. I am looping through each link using *ngFor. What I am trying to achieve looks like this: https://i.sstatic.net/PpY66.png However, what I am currently getting is ...

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

How can I retrieve the Axios error response object within a catch block?

After recently updating to axios version 0.23.0, I encountered an error when attempting to access the error response object in a catch clause. Here is where the issue arises: const loginUser = async (userData: UserPayload): Promise<void> => { ...

How to conceal a column in an Angular Material table

Here is my Angular 2 material table setup: <mat-table #table [dataSource]="dataSource" > <!--- Note that these columns can be defined in any order. The actual rendered columns are set as a property on the row definition" -- ...

Is it possible to import a module that was exported in Node.js using the SystemJS import method?

When working on a Node project, we typically import modules using the require keyword. Is it possible to import the same module in an Angular 2 project using import {} from '', even if the d.ts file is not available? For instance, can I incorpora ...

Executing the pause() function of NgbCarousel in Angular 5 when calling ngOnInit

I recently started learning Angular and using ngbootstrap for my UI development. I am facing an issue with loading the NgbCarousel in pause mode by default. Below is the code snippet that I have attempted: import { Component, OnInit, ViewChild } from ...

Strict mode does not allow duplicate data properties in object literals within JavaScript

Challenge Description I am facing an issue with handling an optional variable called ByteRange. To accommodate this, I included 2 different URLs in the $resource. Upon doing so, I encountered the following error: Message: Error in parsing: "tools/tes ...

Limit the visibility of specific exports to files outside of the directory

Imagine a scenario where there is a directory containing multiple files, each exporting something unique: facade/A.tsx export const _A = () => {...}; // this export should NOT be visible for files outside `facade/` facade/B.tsx export const B = () =&g ...

Performing operations on information within a map function

While using toLocaleString within this map, I encountered an issue where only one of the payment.amount's returned formatted as currency. {props.paymentDates.map((payment, index) => ( <tr key={"payment-" + index}> <td>{i ...

Angular 2 repeatedly pushes elements into an array during ngDoCheck

I need assistance with updating my 'filelistArray' array. It is currently being populated with duplicate items whenever content is available in the 'this.uploadCopy.queue' array, which happens multiple times. However, I want to update ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

When combining Angular with Workbox, you may encounter a ChunkLoadError stating that the loading of a specific chunk was refused to execute due to mismatch

When I added Workbox to Angular for the first production deployment, everything worked smoothly. However, after updating a module, rebuilding Angular, and injecting Workbox again, I encountered an issue. Upon visiting the site, I noticed that the service w ...

"Typescript Conditional Date/String Return Type: Making Informed Return Dec

Is there a way to apply a function that returns either a string or a Date, depending on the type of the value parameter? I'm currently having to use type assertion in the function call <Date>toggleDateString(stringValue) because I keep getting ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

I am attempting to selectively add or remove a line-through style to a single item using Angular

I am facing an issue with my todo list app where I want to apply a line-through style to a specific item only, but currently, the line-through is being applied to all the items in the list instead of just the one I clicked on. HTML <input type="te ...

How can you dynamically disable the submit button on a form in Angular 7+ based on the form's current status?

Let's consider a scenario with a button in our code: <button type="button" class="menu-button" [disabled]="isInvalidForm()">Save</button isInvalidForm() { console.log('I am running!'); return this.nameValidator.errors || this.last ...

Is it necessary to upload items individually using Angular 7 and Asp.net?

I'm encountering an issue where I am trying to send objects to my server, but the objects received have null values. Here is a snippet of the backend code: // Signature public IActionResult Save(string num, string pat, string token, [FromBody]DataC ...

The button icon fails to display correctly on the iPhone X, despite appearing correctly in the DevTools

Recently, I designed a "Scroll to top" button for my application. During testing using Chrome and Safari DevTools, the button appeared correctly on all devices: https://i.sstatic.net/Apb8I.png However, upon opening it on an iPhone X, I noticed that the i ...

What is the best approach to perform type checking on a function that yields varying types depending on the values of its

Currently, I am facing a challenge with a function that takes an argument and returns a different type of value depending on the argument's value. For instance: function foo(arg: 'a' | 'b') { if (arg === 'a') { ret ...

Using HttpClient to retrieve data in formats other than JSON

Error Encountered While Trying to Download Excel File via API I attempted to download an Excel file through an API using a specific method, but unfortunately, I encountered the following error: SyntaxError: Unexpected token P in JSON at position 0 at J ...