我正在尝试将从数据库中获取的数据放入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}`);
}
}
答案 0 :(得分:1)
您必须将lint
放在console.log()
内,因为subscribe
仅在这样完成异步调用后才可用:
accountInfo
答案 1 :(得分:0)
如果您说从数据库很好地接收了数据,则应尝试使用subscribe(如下面的代码)以确保没有错误,并在确定接收到数据时在console.log中打印解决方案。 :
this.accountService.getAccountInfo(this.userId).subscribe(
data => {
this.accountInfo = data;
console.log(this.accountInfo);
},
error => {
console.log(error);
},
() => {
// 'onCompleted' callback.
}
);