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.