How to extract data from SafeSubscriber?

Discussão em 'Angular' iniciado por sad-panda, Março 17, 2025.

  1. sad-panda

    sad-panda Guest

    I have to make an Angular application in which i get data from the back-end and display it on the front-end, but with some added hard-coded data.

    My communication is between 2 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 one: 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 call "this.http.get(clientUrl+"/getText")" I get a SafeSubscriber object, from which i managed to get the data displayed in the console using the method ".subscribe(...)" with a "console.log()" inside of it. However, i did not find any method to extract the data out of this subscribe.

    As the code above shows, i have tried to use pipe and map, but the local variable is returned as [Object object], and when i print it in the console i get either undefined, either nothing.

    This is what my code currently displays:

    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 all the suggestions found in questions below: angular 2 how to return data from subscribe Angular observable retrieve data using subscribe

    Does anyone know a method in which i could get the data out of the Subscribe?

    Continue reading...

Compartilhe esta Página