Unable to access data from Angular Subscribe outside of the method

Discussão em 'Angular' iniciado por Mtullis, Fevereiro 19, 2025.

  1. Mtullis

    Mtullis Guest

    I am pretty new to Angular, and this has me stumped. So I am trying to call to data using a Subscribe, and I am able to console.log that data inside the subscribe method, but I can not access in information outside of it. I believe I am initializing the property correctly (as least this is the way I keep seeing), but I keep get "undetermined". Can someone please show me what I am doing wrong, or give me a better want to fetch the data than a subscribe method?

    @Component({
    selector: 'app-maintain',
    template: '<div [id]="pageId"</div>'
    })

    export class MaintainPage implements AfterViewInit, OnChanges, OnDestroy, OnInit {

    @Select()
    public userName$: any;
    public user: any;
    public pageId = 'maintainPage';
    private readonly destroy$ = new Subject<void>();

    public parentData: any = { message: this.userName$};


    constructor(
    private readonly httpClient: HttpClient,
    private readonly sessionService: SessionService,
    )

    public ngOnInit() {
    this.sessionService.getMySessionUsingGET()
    .pipe(takeUntil(this.destroy$))
    .subscribe((data) => {
    this.userName$ = data.account.name;
    this.user = data;
    console.log("Data: ", data);
    console.log("Name: ", data.account.name);
    }, error => {
    console.log(error);
    });
    console.log('UserName Outside Method: ', this.userName$); // returns "undetermined"
    }


    public ngAfterViewInit(): void {
    this.render();
    }


    public ngOnChanges(changes: SimpleChanges){
    this.render();
    }


    public ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
    }


    private render() {
    const root = createRoot(document.getElementById(this.pageId) as HTMLElement);
    root.render( React.createElement(MaintainWrapper, { ...this.parentData })
    );
    console.log('UserName: ', this.userName$); // returns "undetermined"
    }
    }

    Continue reading...

Compartilhe esta Página