How can I retrieve information from SafeSubscriber?

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!

Answer №1

It appears that the return keyword is missing in your code when mapping the response. Upon reviewing the console.log, it seems like you need to access the text property.

getText(): Observable<any> {
    console.log("it works!");
    return this.http.get(clientUrl+"/getText").pipe(map(res => {
        console.log(res);
        this.optional = res.toString(); 
        return res.text;
    }));
  }

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

What is the best way to write a function in typescript that verifies whether the argument extends a type argument and then returns the argument?

I need to create a function that checks if the argument's type extends a specific type variable and then returns the argument. Something like this: declare function checkType<T, X extends T>(argument: X): X However, TypeScript gives an error wh ...

Angular 5 Pipe fails to run in certain scenarios

I am new to Angular and I have created a custom pipe called "arrayToString" as shown below: import { Pipe, PipeTransform } from '@angular/core'; import * as _ from 'lodash'; @Pipe({ name: 'arrayToString' }) export class Arra ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Utilizing BehaviorSubject to dynamically display components based on conditions

I have a basic Service that looks like this: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class HighlightsService { private _highlightedTab: string = ''; highli ...

What is the best way to generate a graph using JSON data in a Ruby on Rails application?

Currently, I am working on a Ruby on Rails application deployed to Heroku and my goal is to display a simple graph. I am currently using Highcharts for this purpose but I am open to exploring other options that can help me achieve the desired outcome. Bel ...

utilize Java version specifically designed for integrating with Angular framework and SOAP web services

One question I've been pondering: we currently have a project built on Java 6 and GWT, but we're considering migrating to Angular (using SOAP web services). Will Java 6 be compatible with Angular for the backend, or will we need to upgrade to Jav ...

Obtaining POST request parameters in an Express server

Below is the code snippet for adding a product using an angular service. The product is passed as the body. addProduct(product): Observable<any> { return this.http.post<Observable<any>>( `http://localhost:4401/api/products`, ...

The child components of the parent route in Angular 2 are organized as nested route components

Do nested route components act as children of the parent route component? Can they communicate by using an Output from a child route component to the parent route component? If not, what is the suggested approach in this scenario? Since components in rou ...

`Is my JSON contact list missing after running `npm build` in React?`

After creating and deploying my React Web App (NodeJs) online, I noticed that the contact form successfully uploads data to my JSON database using fetch post (localhost:3001). However, when trying to locate the database file after running npm run build i ...

Generating a compressed tar.gz file with a version-specific name using Angular CLI post-build

Here's what I'm trying to do: I want to generate a .tar.gz file once my project is built, and I need the name of the file to be based on the version of the project. I attempted using npm pack, but it only takes the name of the dist folder and cr ...

How can I bypass additional ngIf checks in the Angular template if a variable is null?

I have this code snippet in my template: <div class="icon-action" *ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual" (click)="delete(node)"> ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

Using json-simple to convert multiple JSON strings into objects through parsing

I am currently running a socket server that emits JSON strings for clients. I've been trying to parse these strings using json-simple, but I'm facing an issue because the server does not use any delimiter character to separate the JSON strings. T ...

Navigating with Angular 2 using separate modules but sharing the same routing

What if I have two main routes, both loading the same child module? Is it possible to have two routes with the same name on the child module that load two different components based on the main route? Main Routes: export const ROUTES: Routes = [{ pat ...

What is the best way to create a personalized filter function for dates in JavaScript?

I am working with a DataTable that includes a column called Timestamp: <p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt> <p-column field="timestamp" header="Timestamp" [sortable]=" ...

PHP function stripslashes() causing emojis to break

When I use json_encode and stripslashes on my array, emojis are not displaying correctly. $msg = "Yeah Emojis are cool! ...

Using Ionic 5 to utilize local files for translation while offline

In my Ionic 5 app, I am utilizing translation with the following imports: import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; and loading it like thi ...

Stylish Navigation Menu Logo/Site Name

Currently in the process of upgrading my website and I have my website name included as part of my menu, as opposed to a logo. This has been an easy solution that has worked well for me. For mobile screens, the template I purchased includes a slicknav men ...

Initialization error: ServiceIdentifier Symbol(LicencesService) not found in bindings

Encountering an error while compiling the code: Unable to find matching bindings for serviceIdentifier: Symbol(LicencesService) The issue seems to be in the constructor of the HTTP on server.ts file. How can I properly inject the LicencesService? Here is ...