我有一个服务调用,它返回一组FirebaseListObservable对象。我试图将每个特定的属性(userName)添加到常规的javascript数组中,如下所示:
getUsernames(): string[] {
var userNameArray = [];
this.userList = this.service.getUsers();
this.userList.subscribe(
users => {
users.map(user =>
//console.log(user.userName)
userNameArray.push(user.userName)
)
}
);
console.log(userNameArray[0]);
return userNameArray;
}
这一行
console.log(userNameArray[0]);
打印“未定义”。这是因为subscribe方法的异步性质?如果是这样,我该如何克服这一点?如果没有,为什么不将值添加到数组中?
感谢您的帮助!
编辑:
为清楚起见,以下是从Firebase提取数据的服务代码:
import { Injectable } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TwitchDatabaseService {
userNames: FirebaseListObservable<any[]>;
constructor(private af: AngularFire) {
this.userNames = af.database.list('/userNames');
}
getUsers(): FirebaseListObservable<any[]> {
return this.userNames;
}
答案 0 :(得分:-1)
我认为你可以这样做:
this.service.getUsers().subscribe(
users => return users.map(user => user.userName)
);