I need to develop an Angular application that fetches data from the backend and displays it on the front end, along with some predefined hard-coded data.
The communication in my project happens between two files:
client.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {environment} from "../environments/environment";
import {catchError, map, Observable, of} from "rxjs";
const clientUrl = environment.apiUrl+'client';
@Injectable({providedIn: 'root'})
export class ClientService {
public optional: any;
constructor(private http: HttpClient) {}
getText(): Observable<any> {
console.log("it works!");
return this.http.get(clientUrl+"/getText").pipe(map(res => {
console.log(res);
this.optional = res.toString();
}));
}
}
and the second file: client.component.ts
import { Component, OnInit } from '@angular/core';
import {ClientService} from "../client.service";
@Component({
selector: 'app-client',
templateUrl: './client.component.html',
styleUrls: ['./client.component.css']
})
export class ClientComponent implements OnInit {
public textResponse: any;
constructor(public service: ClientService) {}
ngOnInit(): void {}
getText() {
let text: any;
this.textResponse = this.service.getText().subscribe();
console.log(this.textResponse);
text = this.textResponse + "This text is added from code.";
console.log(text);
}
}
When I make a call to "this.http.get(clientUrl+"/getText")", I receive a SafeSubscriber object. I have managed to display the retrieved data in the console using the ".subscribe(...)" method with a "console.log()" inside it. However, I'm struggling to extract the data out of this subscribe functionality.
In the code above, I attempted to use pipe and map, but the local variable returned as [Object object], and when I print it in the console, it shows either undefined or nothing.
This is the current output of my code:
it works! [client.service.ts:33]
SafeSubscriber {initialTeardown: undefined, closed: false, _parentage: null, _finalizers: Array(1), isStopped: false, …} [client.component.ts]
[object Object]This text is added from code. [client.component.ts]
{text: 'This text is read from a file.'} [client.service.ts]
I have also tried implementing suggestions found in similar questions below: angular 2 how to return data from subscribe Angular observable retrieve data using subscribe
If anyone knows a way to effectively extract the data from the Subscribe function, your input would be greatly appreciated!