简体   繁体   中英

'Angular5' Service (rxjs/observable) two components rendering issue

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM