简体   繁体   中英

data not accessible outside of subscription function

I am passing data between components onload. When the component receives the information within the subscribe function it is able to use the data and do whatever with it, so a console.log works fine, so it is clearly receiving it, but immediately outside of the subscribe function the information is unaccessible and is undefined. So I can't run a console.log or do anything with the information. In the html, it says that it is undefined as well.

The component.

import { Observable } from 'rxjs/Rx';
import { User } from '../User';
import { AccountInfo } from './../AccountInfo';
import { LoginService } from './../login.service';
import { Component, OnInit, AfterViewInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit, AfterViewInit {

public user: User;
public subscription: Subscription;

  constructor(route: ActivatedRoute, private loginService: LoginService) {}

  ngOnInit() {
    this.loginService.getMessage().subscribe(data =>
    {
      this.user = data;
      console.log(this.user.vendorname);
     });

    console.log(this.user.vendorname);

  }

  ngAfterViewInit() {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.
    }  

  }

relevant section of html

<h1>Welcome {{user.vendorname}}</h1>

Yes.. that's how async functions work. The thing you pass into the subscribe function is another function.

data => {
  this.user = data;
  console.log(this.user.vendorname);
}

This will be called once the getMessage() has received answer from your server. Any statements after the subscribe will be called immediately, and that's why this.user.vendorname is still undefined when you try to log it there.

If you are receiving an error in your html you should use the safe navigation operator ( ?. ):

<h1>Welcome {{user?.vendorname}}</h1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM