How to set a value from observable to a variable in Angular 2

Discussão em 'Angular' iniciado por Sol, Fevereiro 26, 2025.

  1. Sol

    Sol Guest

    I have a UsernameService that returns an observable which contains a json object. In AnotherService, I want to inject a value from the UsernameService object.

    So far, I am able to subscribe to the observable from UsernameService and I can show it in the console. I can even drill down and show one of the values from the object in the console. However, I don't understand how to assign that value to a variable that I can then use. Instead, when I try to assign the value to a variable, in the console I get: Subscriber {closed: false, _parent: null, _parents: null...etc

    Here's my example where I am successfully showing the observable value in the console:

    import { UsernameService } from './username.service';
    import { Injectable, OnInit } from '@angular/core';
    import 'rxjs/Rx';

    @Injectable()
    export class AnotherService {

    username: any[] = [];

    constructor(private getUsernameService: UsernameService) { }

    someMethod() {
    let myFinalValue = this.getUsernameService.getUsername()
    .subscribe(username => console.log(username.data[0].AccountName));
    }
    }


    The code above results in the console correctly showing the value of the AccountName field which I am trying to assign to the variable myFinalValue. However, I cannot seem to figure out where I am going wrong.

    When I try to use the same technique to simply get the value (instead of log in console), I get the generic: Subscriber {closed: false, _parent: null, _parents: null...etc as I mentioned before.

    Here's an example of the code that results in my error:

    import { UsernameService } from './username.service';
    import { Injectable, OnInit } from '@angular/core';
    import 'rxjs/Rx';

    @Injectable()
    export class AnotherService {

    username: any[] = [];

    constructor(private getUsernameService: UsernameService) { }

    someMethod() {
    let myFinalValue = this.getUsernameService.getUsername()
    .subscribe(username => this.username = username.data[0].AccountName);
    console.log(myFinalValue);
    }
    }


    Ultimately, my goal is to just assign the value from username.data[0].AccountName to the variable myFinalValue.

    Thanks in advance for your help!

    Continue reading...

Compartilhe esta Página