Convert an observable to a local array

0

Save the value of the observable array in a local array and use it to add more users, since the remote server link it does not allow to edit the data, it is test.

user.component.ts

users: User[];

getUsers() {
  return this.userService.getUsers().subscribe(users => this.users = users);
}

user.service.ts

getUsers(): Observable<User[]> {
  return this.http.get<User[]>('http://jsonplaceholder.typicode.com/users');
}

I do not know if I'm going wrong, but the idea that I have would be to obtain the data from the remote database only when the variable of the local array is empty and from there, manipulate the data from said local variable.

getUsers() {
  if (this.users == null) {
    this.users = this.userService.getUsers()
                                 .subscribe(users => this.users = users as User[]);
  }
  return this.users;
}
    
asked by Rawsky 26.06.2018 в 14:50
source

1 answer

1

If you want to store the data that comes from the remote server and then modify it, the best way is to store it in the localstorage and from there you can edit, add or delete.

Example:

  getUsers() {
    if (localStorage.getItem('user') == undefined) {
      return this.http.get('https://jsonplaceholder.typicode.com/users').pipe(
            map(resultados => {

                localStorage.setItem('user', JSON.stringify(resultados));

              return resultados;
            }));
    }
    else {
      return Observable.of(JSON.parse(localStorage.getItem('user')));
    }
  }

So if you want to delete a user simply access the localstorage, delete the user you want and save it again. I hope it serves you

    
answered by 26.06.2018 / 15:48
source