Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use map and console.log my variable, it shows as an Observable but does not display in my template.

<div class="col-6" *ngIf="courseDatas$ | async as courses else NoData">
  <div class="card" *ngFor="let course of courses">
    <div class="card-body">
      <span><strong>User ID is : </strong>{{course.userId}}</span><br>
      <span><strong>Title is : </strong>{{course.title}}</span><br>
      <span><strong>Body is : </strong>{{course.body}}</span><br>
      <span><strong>ID is : </strong>{{course.id}}</span>
    </div>
    <ng-template #NoData>No Data Available</ng-template>
  </div>
</div>

App component :

import {Component, OnInit} from '@angular/core';
import {PostsService} from "./posts.service";

import {Observable} from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  courseDatas$ : Observable<any>;

  constructor(private posts : PostsService){}


  ngOnInit(){
    this.courseDatas$ = this.posts.getData();

  }
}

posts Service :

import { Injectable } from '@angular/core'
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
import {map} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class PostsService {

  private postURL: string = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get(this.postURL).pipe(
      map(data => {
        for (let datas of (data as Array<any>)){
          datas.title = datas.title + "Hey";
        }
      }),
    );
  }

Despite logging the Observable in App.Component correctly, the data doesn't show up using the async pipe in the template when I use the map operator in the service's getData method. Strangely, when I add console.log(datas.title) inside the map operator, it logs every title with "Hey" at the end.

Answer №1

map should be used to return a value that will mutate the current property. In this case, it seems like you should return the data.

getData(): Observable<any> {
    return this.http.get(this.postURL).pipe(
      map(data => {
        for (let datas of (data as Array<any>)){
          datas.title = datas.title + "Hey";
        }
        return data;
      }),
    );
}

Alternatively, you can use Array.prototype's map instead of a for loop to mutate your data:

getData(): Observable<any> {
    return this.http.get(this.postURL).pipe(
      map(data => data.map(d => (d.title = d.title +"Hey", d));
      }),
    );
 }

Remember: if curly braces are missing in an arrow function, it will return automatically.

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

Guide on adding a post type via the command line: Issue encountered - Anticipated POST console HTML error

Facing Error: EXPECTED POST in JQuery Ajax Call Encountering the same issue as mentioned in the provided link. The need is to switch from GET to POST, but direct alteration of ajax code is not feasible. It must be done dynamically using JavaScript through ...

Exploring TingoDB: Trouble encountered when passing global variable to insert operation

During my testing and benchmarking of several embedded databases using node.js, I have encountered an interesting issue with TingoDB. Does anyone have insight into why the following code snippet works as expected: var test = { hello:'world' }; f ...

Instructions on activating the standard scrolling function for a specific DIV element

I'm struggling to achieve a specific scrolling effect on my one-page website. I want the initial section to be displayed as a full page, and when the user scrolls down, it should transition to the next section with a full page scroll. However, once th ...

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

Show the values in the second dropdown menu according to the selection made in the first dropdown menu using Angular 8

My goal is to retrieve data and populate two dropdowns based on user selection. However, the code I've written isn't giving me the desired output and instead, errors are occurring. Being new to Angular, I would appreciate a review of my code. Her ...

"Implementing database updates with AJAX and utilizing the PUT method: a step-by-step guide

I am attempting to update a database property named "Estado" using ajax. Here is the code I am using: function updateDatabaseProperty(idMarker, newState) { $.ajax ({ url: `/api/IgnicoesAPI/${idMarker}`, type: 'PUT ...

File upload not functioning correctly with Angular 7 MEAN stack when using multer middleware

I am currently using the multer middleware for file upload in my Angular mean stack project. However, I am facing an issue where I am unable to retrieve req.file but can successfully access req.body, indicating that the file is not being uploaded. When I c ...

How to implement ngx-infinite-scroll in Angular 4 by making a vertically scrollable table

Looking for a way to make just the table body scrollable in Angular 4 using ngx-infinite-scroll. I've tried some CSS solutions but haven't found one that works. Any help or documentation on this issue would be greatly appreciated. I attempted th ...

Optimal approach for vertically aligning elements in CSS

I'm looking to arrange my header ('Sail away today with Starboard Rentals.') and link buttons on top of each other. I want the navigation buttons to be positioned below the h1 on the lower half of the 'home-jumbo' div. What's ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

At times, the Ajax response may be lacking in content. However, the response tab in Google

My goal is to retrieve responses from an AJAX call and store them in the global scope for easy access throughout my website. var getOrderStatus = getOrderStatus(), getUserData = getUserData(), orderFormReady = $.when(getOrderStatus, getUserData), ...

Encountered an issue while trying to install and run an Angular app: Error code TS2694 indicates that the Namespace does not have an exported member '

Attempting to construct and execute this angular project. Post building the project, with npm i I encountered some warnings, but no errors were found. After executing ng serve -o, the following errors appeared. Moreover, when accessed through the browser, ...

Is there a way to dynamically integrate the Insert Column feature into the ContextMenu of a Syncfusion Treegrid?

What is the best way to add Insert Column functionality to the ContextMenu of a Syncfusion Treegrid? Insert Column Rename Column Delete Column ...

Troubleshooting ng module not found error when deploying Typescript + Angular app on Azure App Service using Azure DevOps pipeline

My Typescript and Angular application runs perfectly when tested locally. Now, I'm in the process of setting up a deployment pipeline using Azure DevOps to build and release it to an App Service running on Linux (Node.js web app). Although the pipel ...

Using SystemJS to re-export modules does not function properly

Attempting to re-export modules according to the TypeScript language website - using SystemJS as the module loader: app.ts import * as s from "./AllValidators"; // Some samples to try let strings = ["Hello", "98052", "101"]; // Validators to use let v ...

Delete all HTML functionalities

Is there a way to strip HTML functions when using a text area so that the content shows as plain text in a new post (div)? For example, if I type "Hello", I want it to appear as "< b > Hello < b / >", showing the whole code. Here is the code ...

How to showcase the array object nested within an array of objects in Angular 2

Here is the content of my JSON file: country_id:String, name:String scholardetails:[{ country_id:String, scholarshipname:String, scholarshiplink:String }] ...

Enhancing React Functionality: Increasing React State Following an If Statement

Whenever I click on the start/stop button, it triggers the handlePlay function. This function then proceeds to initiate the playBeat function. In an ideal scenario, the play beat function should continuously display 1222122212221222... until I press the st ...

What are the steps to properly build and implement a buffer for socket communication?

I have encountered an issue while converting a code snippet to TypeScript, specifically with the use of a Buffer in conjunction with a UDP socket. The original code fragment is as follows: /// <reference path="../node_modules/DefinitelyTyped/node/node ...