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.
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
UserList
component: https://github.com/TomerOmri/angular-users-map/blob/master/test-app/src/app/userlist/userlist.component.ts
UserMap
component: https://github.com/TomerOmri/angular-users-map/blob/master/test-app/src/app/usersmap/usersmap.component.ts
User
Service:
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.