log from web不知道为什么第41行未定义。只想将值赋给局部变量“users”。 能够将值分配给变量或在订阅函数内记录。
这是角度代码:
export class UserProfileComponent implements OnInit {
id = '';
users;
constructor(private route: ActivatedRoute,
private afs: AngularFirestore,
private afsauth: AngularFireAuth,
public Auth: AuthService) { }
ngOnInit() {
const collection: AngularFirestoreCollection<any> = this.afs.collection('users');
// Notice how the observable is separated from write options
const collection$: Observable<any> = collection.valueChanges();
collection$.subscribe(data => console.log(data));
this.getuid();
}
//this.user = this.afsauth.auth.currentUser
getuid(){
this.Auth.user.subscribe((data:any) => {
this.users = data.uid;
console.log(data);
console.log(this.users);
});
console.log(this.users);
}
}
答案 0 :(得分:3)
我假设问题行在这里:
getuid(){
this.Auth.user.subscribe((data:any) => {
this.users = data.uid
console.log(data)
console.log(this.users)
});
console.log(this.users) // <-- Line generating the error?
}
这样做的原因是,当执行此代码时,会立即执行subscribe,然后执行最后一个console.log
语句。此时,this.users
未定义。
当订阅发出值时,将执行订阅中的代码。只有这样才能设置this.users
属性。