Reputation: 914
I have a component where I put some data inside a variable users
to read it in another function. When I print this variable inside constructor and print it on my console I can see it, but when I do the same inside another function I got undefined. I already tried to declare it as private and public and get the same result.
How can I declare this variable to see it inside another method?
this is my component:
import { tap, take, map } from 'rxjs/operators';
...
export class SharedProofsComponent implements OnInit {
page = 1;
pageSize = 4;
collectionSize = COUNTRIES.length;
countries: User[];
users: User[];
constructor(private firestore: AngularFirestore) {
this.firestore.collection<User>('users').valueChanges().pipe(take(1)).subscribe(users => {
this.users = users;
// console.log(this.users);
this.refreshCountries();
});
}
refreshCountries() {
console.log("USERS:");
console.log(this.users); // here I got undefined
this.countries = this.items
.map((country, i) => ({id: i + 1, ...country}))
.slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);
}
ngOnInit(): void {
}
}
EDIT:
If I put a static constant on my function I can get the data:
this.countries = COUNTRIES
.map((country, i) => ({id: i + 1, ...country}))
.slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);
But if I do this:
this.countries = this.items
.map((country, i) => ({id: i + 1, ...country}))
.slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);
I got the error:
Property 'map' does not exist on type 'Observable<User[]>'. .map((country, i) => ({id: i + 1, ...country}))
Upvotes: 0
Views: 691
Reputation: 1301
Add this.refreshCountries();
inside the subscribe callback, so that. it becomes:
this.firestore.collection<User('users').valueChanges().pipe(take(1)).subscribe(users => {
this.users = users;
this.refreshCountries()
});
Upvotes: 3
Reputation: 172
You call method before getting data and besides you fetch users asynchronously. When you call refreshCountries
no any data in users
variable.
Should work
this.firestore.collection<User>('users').valueChanges().pipe(take(1)).subscribe(users => {
this.users = users; // get users
this.refreshCountries(); // call method
});
Upvotes: 3
Reputation: 156
You have to be careful because when you are fetching the data with the subscribe in firestore in the constructor method it is a async call. If you are using the refreshCountries function before the request is resolved, you cannot see the result properly.
Upvotes: 1