Seeker C
Seeker C

Reputation: 67

Unable to pass data from indexedDB to an Angular Subject for use in an Observable using ngx-indexed-db

After I call getByKey using ngx-indexed-db from indexedDB I want to pass the data to the subject. I can see the data is being called but when I use next, i'm being told the data is undefined.

public userInfo = new Subject<any>();

 getData(){ 
    var db = new NgxIndexedDB('jwt', 1);    
    db.openDatabase(1).then(function() {
      db.getByKey('token', 1).then(
        (res) => {
            // Do something after the value was added
            console.log(res); //data populates in the console
            this.userInfo.next(res) // this step I receive undefined error
        },
        error => {
            console.log(error);
        }
    );
  }

watchUser(): Observable<any> {
  return this.userInfo.asObservable();        
};

getUserInfo(){
  this.watchUser().subscribe(res => console.log(res))
}

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'userInfo' of undefined TypeError: Cannot read property 'userInfo' of undefined

enter image description here

In line 118 you can see the console.log shows the data is being pulled from indexedDB, in line 119 you can see no data is being passed and is coming through as undefined. I'm expecting to pass data from indexedDB to be used by observable for use in the rest of the application.

Upvotes: 1

Views: 937

Answers (2)

dumbmatter
dumbmatter

Reputation: 9673

    db.openDatabase(1).then(function() {

That line changes what this is inside that function. Try changing it to this:

    db.openDatabase(1).then(() => {

There could be other problems, I don't know anything about Angular or observables, but that's definitely one problem.

Upvotes: 2

Rushi Patel
Rushi Patel

Reputation: 601

Can you please check with BehaviorSubject?Maybe it will be helpful.Don't forget to import it.

public userInfo = new BehaviorSubject<any>('');

Upvotes: 0

Related Questions