0

I have a master list app with two component: usersList and usersMap both of which, are holding a private users variable, that gets its data from the service.

Both are subscribed to a users-service that has a Users array with users data.

Every change on this array will cause both components to render and update their users variable.

Photo of the app on runtime

When I create a new user, the users array gets updated, and the usersList gets re-rendered, but the usersMap isn`t.

I tried some solutions provided on stack, but they didn't work. for example: Angular2 Observable BehaviorSubject service not working

A link to the github: https://github.com/TomerOmri/angular-users-map/tree/master/test-app/src/app

    import { Injectable } from '@angular/core';
    import { Observable } from "rxjs/Observable";
    import { of } from "rxjs/observable/of";
    import { User } from "./user";
    import { USERS } from "./users-mock";
    
    @Injectable()
    export class UserService {
      constructor() { }
      getUsers(): Observable<User[]> {
        var userList = of(USERS);
        return userList;
      }
    
    }
Olivier Pons
  • 15,363
  • 26
  • 117
  • 213
Tomz
  • 771
  • 5
  • 6

1 Answers1

0

Use following code to do your task:

@Injectable()
export class UserService {
  private userList = USERS;
  public users = new BehaviourSubject<any>(userList);
  constructor() { }

  addUser(user): {
    this.userList.push(user);
    this.users.next(this.userList);
  } 

Now use this users property in your both component to get data. When you need to add just call addUser method of service. Hope it will help.

Sandip Jaiswal
  • 3,428
  • 2
  • 13
  • 15
  • Thanks! what is 'BehaviourSubject'? the class doesn`t know it. and the function I need is "get Users" not to add, how should I do it? – Tomz Dec 29 '17 at 14:05