开发者问题收集

.subscribe 不会将数据放入我的数组中

2019-01-10
260

我试图将从数据库获得的数据放入 accountInfo 数组中。我确信数据是从数据库获得的,但当我记录数组时,它是空的。我试过了所有方法,但还是搞不清楚为什么它不起作用。

account.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { AccountService } from './account.service';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { AccountInfo } from './accountListItem';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss'],
  providers: [AccountService],
})
export class AccountComponent implements OnInit {

  public accountInfo = [];
  public userId: string;
  constructor(private accountService: AccountService) { }

  ngOnInit() {
    this.userId = localStorage.getItem('user_id');
    this.accountService.getAccountInfo(this.userId)
    .subscribe(data => this.accountInfo = data);
    console.log(this.accountInfo);
  }
}

account.service.ts

import { Injectable } from '@angular/core';
import { Observable , of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { AccountInfo } from './accountListItem';
import { environment } from '../../environments/environment';

@Injectable()
export class AccountService {
  constructor(private http: HttpClient) {}

  getAccountInfo(userId: any): Observable<AccountInfo[]> {
    return this.http.get<AccountInfo[]>(`${environment.apiUri}/user?userid=${userId}`);
  }
}
2个回答

您必须将 console.log() 放在 subscribe 中,因为 accountInfo 仅在异步调用完成后才可用,如下所示:

ngOnInit() {
  this.userId = localStorage.getItem('user_id');
  this.accountService.getAccountInfo(this.userId)
  .subscribe(data => {
    this.accountInfo = data;
    console.log(this.accountInfo);
  });
}
Korfoo
2019-01-10

如果你说你从数据库顺利地接收到了数据,你应该尝试使用订阅(如下面的代码)来确保你没有错误,并在你确定接收到数据时在 console.log 中打印解决方案:

this.accountService.getAccountInfo(this.userId).subscribe(
     data => {
        this.accountInfo = data;
        console.log(this.accountInfo);
    },
     error => {
        console.log(error);
    },
     () => {
        // 'onCompleted' callback.
    }
);
JoseJimRin
2019-01-10