离子存储未定义为对象数组

时间:2017-10-08 17:55:32

标签: angular typescript ionic-framework ionic3

我正在努力获取我从Parse Server中检索到的一个对象数组,但没有成功。

我正在使用Ionic 3和Ionic Storage构建应用程序。似乎我得到了一个承诺而不是价值,但我已经尝试了一切来解决它。

我的search.ts文件:

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();
  }
  }

和我的Data.ts文件:

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);
}

}

当我尝试运行它时,第一个控制台日志返回用户数组,但第二个,我需要的是未定义的。

我该怎么办?

我很抱歉代码的大部分内容

非常感谢

最新代码

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;
  //}
}

和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);
}

}

旧代码工作

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;
  //}
}

和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;
          });
    }  

}    

1 个答案:

答案 0 :(得分:0)

您无法像这样访问该值,因为这些是Async次操作。您可以尝试如下所示。

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);
      });

     });
   });
  }
 }