简体   繁体   中英

Ionic Storage Undefined for Array Of Objects

I am struggling to get an array of object I have retrieved from my Parse Server but no success.

I am building the app with Ionic 3 and Ionic Storage. It seems that I got a promise instead of value but I have tried everything to fix it.

My search.ts file:

import { Data } from './../../services/data';
import { localData } from './../../services/local';
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Parse } from 'parse';
import 'rxjs/add/operator/map';
import {User} from '../../models/User';
import 'rxjs/add/operator/debounceTime';
import {FormControl} from '@angular/forms';

@Component({
selector: 'page-search',
templateUrl: 'search.html',

})

export class SearchPage {
currentUser = Parse.User.current();
query1 = new Parse.Query('Friends');
friendQuery = new Parse.Query('Friends');
query = new Parse.Query(Parse.User);
tmp: any =[];
users: any= [];
user: any =[];  

initializeItems() {
this.users = this.dataService.tmpusers;

}

retrieveUsers(){
if (this.currentUser= Parse.User.current()) {
  Parse.Cloud.run('UserQuery').then(
  res => {
    console.log('user query')
    this.tmp = res;
    console.log(this.tmp);
    this.dataService.setUsers2(this.tmp);
    this.users = this.dataService.tmpusers;
    console.log(this.users);

  }
  )
  }
  }

  retrieveFriends(){
  if (this.currentUser= Parse.User.current()) {
  Parse.Cloud.run('FriendsQuery', {currentuser: 'fEjQgAPvDO'}).then(
  res => {
    console.log(res)
    }
  )
  }     
  }

  constructor(public navCtrl: NavController, private localdata: localData, 
  private dataService: Data) {
  this.searchControl = new FormControl;

  }

  showUsers: any = false;
  searchControl: FormControl;
  searchTerm: string = '';
  searching: any = false;

  filterusers(searchTerm){ 
    return this.users.filter((user) => {
        return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) 
   > -1;
    });    
  }

  ionViewDidLoad() {
  this.retrieveFriends();
  this.retrieveUsers();
  this.setFilteredItems();
  this.searchControl.valueChanges.debounceTime(700).subscribe(search => {
  this.searching = false;
  this.setFilteredItems();
   });
  }

  onSearchInput(){
  this.searching = true;
  }

  setFilteredItems() {
  this.initializeItems();
  this.users = this.filterusers(this.searchTerm);
  }  

  onCancel(ev: any) {
  this.initializeItems();
  }
  }

and my Data.ts file:

import { Storage } from '@ionic/storage';
import { Injectable, Component } from '@angular/core';

@Injectable()
export class Data {

tmpusers = this.getUsers2();

constructor(public storage: Storage){

}

getUsers2() {
this.storage.get('users');
}

setUsers2(users){
this.storage.set('users', users);
}

}

When I am trying to run this, the first console log returns me the array of the users but the second one, which I need is undefined.

What can I do?

I am sorry for the large part of code

Thank you very much

latest code

import { Data } from './../../services/data';
import { localData } from './../../services/local';
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Parse } from 'parse';
import 'rxjs/add/operator/map';
import {User} from '../../models/User';
import 'rxjs/add/operator/debounceTime';
import {FormControl} from '@angular/forms';



@Component({
  selector: 'page-search',
  templateUrl: 'search.html',

})

export class SearchPage {
  currentUser = Parse.User.current();
  query1 = new Parse.Query('Friends');
  friendQuery = new Parse.Query('Friends');
  query = new Parse.Query(Parse.User);
  tmp: any =[];
  users: any= [];
  user: any =[];  



initializeItems() {

    this.users = this.dataService.newusers;
    }

retrieveUsers(){
  if (this.currentUser= Parse.User.current()) {
    Parse.Cloud.run('UserQuery').then(
    res => {
      console.log('user query')
      this.tmp = res;
      console.log(this.tmp);
      this.dataService.setUsers2(this.tmp).then(()=>{
          this.dataService.getUsers2().then((val)=>{
           this.users = val;
            console.log(this.users);
        });

       });
     });
    }
   }




retrieveFriends(){
    if (this.currentUser= Parse.User.current()) {
      Parse.Cloud.run('FriendsQuery', {currentuser: 'fEjQgAPvDO'}).then(
      res => {
        console.log(res)
        }
      )
    }
   }

  constructor(public navCtrl: NavController, private localdata: localData, private dataService: Data) {
      this.searchControl = new FormControl;
  }

  showUsers: any = false;
  searchControl: FormControl;
  searchTerm: string = '';
  searching: any = false;

  filterusers(searchTerm){ 
        return this.users.filter((user) => {
            return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
        });    
     }

  ionViewDidLoad() {
    this.retrieveFriends();
    this.retrieveUsers();
    this.setFilteredItems();
    this.searchControl.valueChanges.debounceTime(700).subscribe(search => {
      this.searching = false;
      this.setFilteredItems();
       });
  }

  onSearchInput(){
    this.searching = true;
    //this code is to hide users until input is triggered
    //if (this.searchTerm.length >=1)
   // return this.showUsers= true;
   // else {
   //   return this.showUsers = false;
   // }
    //end of code
  }

  setFilteredItems() {
    this.initializeItems();
    this.users = this.filterusers(this.searchTerm);
  }  

  onCancel(ev: any) {
    this.initializeItems();
  }

  //searchfriends() {
   // this.friendQuery = new Parse.Query.or(this.query1.equalTo('fromUser',Parse.User.current()),this.query1.equalTo('toUser',Parse.User.current()));
    //let users = this.query.find();
    //return this.users;
  //}
}

and the data.ts

import { Storage } from '@ionic/storage';
import { Injectable, Component } from '@angular/core';

@Injectable()
export class Data {
newusers = [];

    tmpusers = this.getUsers2();

  constructor(public storage: Storage){
    }

    getUsers2(): Promise<any> {
      return this.storage.get('users');
    }  

 setUsers2(users): Promise<any> {
  return this.storage.set('users', users);
}

}

old code working

import { Data } from './../../services/data';
import { localData } from './../../services/local';
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Parse } from 'parse';
import 'rxjs/add/operator/map';
import {User} from '../../models/User';
import 'rxjs/add/operator/debounceTime';
import {FormControl} from '@angular/forms';



@Component({
  selector: 'page-search',
  templateUrl: 'search.html',

})

export class SearchPage {
  currentUser = Parse.User.current();
  query1 = new Parse.Query('Friends');
  friendQuery = new Parse.Query('Friends');
  query = new Parse.Query(Parse.User);
  tmp: any =[];
  users: any= [];
  user: any =[];  

  initializeItems() {
   this.users = this.localdata.tmpusers;

    }


   retrieveUsers(){
   if (this.currentUser= Parse.User.current()) {
    Parse.Cloud.run('UserQuery').then(
   res => {
   console.log('user query')
   this.tmp = res;
   console.log(this.tmp);
   this.localdata.setUsers(this.tmp);
   this.users = this.localdata.tmpusers;
   console.log(this.users);

  });
  }
  }

 retrieveFriends(){
    if (this.currentUser= Parse.User.current()) {
      Parse.Cloud.run('FriendsQuery', {currentuser: 'fEjQgAPvDO'}).then(
      res => {
        console.log(res)
        }
      )
    }
   }

  constructor(public navCtrl: NavController, private localdata: localData, private dataService: Data) {
      this.searchControl = new FormControl;
  }

  showUsers: any = false;
  searchControl: FormControl;
  searchTerm: string = '';
  searching: any = false;

  filterusers(searchTerm){ 
        return this.users.filter((user) => {
            return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
        });    
     }

  ionViewDidLoad() {
    this.retrieveFriends();
    this.retrieveUsers();
    this.setFilteredItems();
    this.searchControl.valueChanges.debounceTime(700).subscribe(search => {
      this.searching = false;
      this.setFilteredItems();
       });
  }

  onSearchInput(){
    this.searching = true;
    //this code is to hide users until input is triggered
    //if (this.searchTerm.length >=1)
   // return this.showUsers= true;
   // else {
   //   return this.showUsers = false;
   // }
    //end of code
  }

  setFilteredItems() {
    this.initializeItems();
    this.users = this.filterusers(this.searchTerm);
  }  

  onCancel(ev: any) {
    this.initializeItems();
  }

  //searchfriends() {
   // this.friendQuery = new Parse.Query.or(this.query1.equalTo('fromUser',Parse.User.current()),this.query1.equalTo('toUser',Parse.User.current()));
    //let users = this.query.find();
    //return this.users;
  //}
}

and the local.ts

import { Component } from '@angular/core';

export class localData {

    setUsers (users){
        window.localStorage.users_data = JSON.stringify(users);
    }
    getUsers(){
       return JSON.parse(window.localStorage.users_data || '[]');
    }

    tmpusers = this.getUsers();
    constructor(){
        this.tmpusers.sort(function(a, b) {
            var nameA = a.username.toUpperCase(); // ignore upper and lowercase
            var nameB = b.username.toUpperCase(); // ignore upper and lowercase
            if (nameA < nameB) {
              return -1;
            }
            if (nameA > nameB) {
              return 1;
            }

            return 0;
          });
    }  

}    

You cannot access that value like that since those are Async operations.You can try as shown below.

data.ts

getUsers2(): Promise<any> {
  retrun this.storage.get('users');
}

setUsers2(users): Promise<any> {
   return this.storage.set('users', users);
}

search.ts

retrieveUsers(){
if (this.currentUser= Parse.User.current()) {
  Parse.Cloud.run('UserQuery').then(
  res => {
    console.log('user query')
    this.tmp = res;
    console.log(this.tmp);
    this.dataService.setUsers2(this.tmp).then(()=>{
        this.dataService.getUsers2().then((val)=>{
         this.users = val;
          console.log(this.users);
      });

     });
   });
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM