Angular2-indexeddb如何从查询中返回值

时间:2017-04-27 15:18:33

标签: angular return components indexeddb

我想从数据库中获取所有用户,为此我这样做:

// Get all users in the database.
getAllUsers() { 
this.db.getAll('users').then((users) => {
  console.log(users); //this logs all the users in the console.
}, (error) => {
  console.log(error);
});
}

在我的组件中我这样做:

// input the result in the array.
const users: any = this.i.getAllUsers();

如果我尝试:

// Get all users in the database.
getAllUsers() { 
this.db.getAll('users').then((users) => {
  return users; //i don't get a return value...
}, (error) => {
  console.log(error);
});
}

我没有任何回报价值......

如果我这样做:

return this.db.getAll('users');

我得到整个方法对象......

3 个答案:

答案 0 :(得分:0)

也许我在想基本但如果你把它放在一个变量中它会起作用吗?

// Get all users in the database.
getAllUsers() { 
this.db.getAll('users').then((users) => {
  var allUsers = users; // <-here
}, (error) => {
  console.log(error);
});

答案 1 :(得分:0)

试试这个

getAllUsers() { 
 return this.db.getAll('users').then((users) => {
    return users;
   }, (error) => {
        console.log(error);
   });
}

答案 2 :(得分:0)

问题解决了。

  constructor(private r: ComponentFactoryResolver,
          private rs: RestService,
          private d: DataService,
          private i: IndexedDBService
) {
this.c = r.resolveComponentFactory(ChooseAccountProfileComponent);
this.db = new AngularIndexedDB('usersDB', 1);

this.db.createStore(1, (evt) => {
  const objectStore = evt.currentTarget.result.createObjectStore('users', {keyPath: 'id', unique: true});

  objectStore.createIndex('remembered', 'remembered');

}).then(() => {
  this.getAllUsers();
}, (error) => {
  console.log(error);
});
}

// Get all users in the database.
getAllUsers() {
this.db.getAll('users').then((users) => {
  let oldcounter = 0;
  const kleurenArray = ['#1ccc49', '#e10d6d', '#11afe0', '#7dd317', '#d95f16', '#b0990d', '#7510cc'];

  for (let i = 0; i < users.length; i++) {
    // put the json in an object.
    const obj = users[i];
    // Make the component.
    const cmpRef = this.v.createComponent(this.c);
    // Fill the component with the correct values.
    cmpRef.instance.name = obj.username;
    cmpRef.instance.id = obj.id;
    do {
      var counter = Math.floor(Math.random() * 7);
    }
    while (oldcounter === counter);
    oldcounter = counter;
    cmpRef.instance.image = '../../../assets/images/Avatars/avatar-    bg-col' + counter + '.png';
    cmpRef.instance.color = kleurenArray[counter];
  }
}, (error) => {
  console.log(error);
});
}

我必须将所有方法放在同一个组件中,然后我才能使用该变量。不管怎样,谢谢!