首页 > 解决方案 > 日志声明变量内容角度7

问题描述

我有一个名为 currentUser 的声明变量,其中包含一个来自 http get 请求的用户对象,我只想记录 currentUser 变量,但我没有定义!有人可以解释一下为什么!

import { Component, OnInit, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';    
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  currentUser: any;
  user: FormGroup;
  cities: any[];
  fileToUpload: any;
  avatarPath: any;
  avatarURL: any;
  returnUrl: any;

  constructor(
    private http: HttpClient,
    private fb:FormBuilder
  ) {
   this.createForm();
  }

  ngOnInit() {

    this.http.get('api/user').subscribe(user => {
      this.currentUser = user;
      localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
    });
    console.log('this.currentuser :', this.currentUser)    
    this.http.get('api/cities').subscribe((cities: any[]) => {
      this.cities = cities;
    });
    this.user.patchValue({
      firstName: this.currentUser.firstName,
      lastName: this.currentUser.lastName,
      email: this.currentUser.email,
      profession: this.currentUser.profession,
      gender: this.currentUser.gender,
      birthDate: this.currentUser.birthDate,
      phone: this.currentUser.phone,
      oldPassword: this.currentUser.oldPassword,
      password: this.currentUser.newPassword,
      address: this.currentUser.address,
      postalCode: this.currentUser.postalCode,
      city: this.currentUser.city._id
    });
  }

标签: angulartypescripthttpvariables

解决方案


我认为这是因为同步而发生的。尝试这个:

this.http.get('api/user').subscribe(user => {
    this.currentUser = user;
    console.log('this.currentuser :', this.currentUser);
    localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
});


推荐阅读