Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2, keep models sync between components

I'm considering moving to Angular2 from my trusted backbone (or should I say, my boss wants to play with a new toy, which is fine by me), I searched a lot online and made some tests but I can't seem to find the answer to this simple question:

Can I keep 2 models in sync between two components ? Exemple: I have a list of users on the sidebar, which is one component, and a form to edit said users in my "main page", which is another component.

The sidebar is responsible for getting its collection to display, and the form is responsible for getting its model. When the model is updated, I want the changes to be reflected in the sidebar, without going through the server again.

I know SpinJS does this and I hacked something in Backbone using events to achieve the same thing (based on model class and id), but I wonder if Angular2 has a native way of handling that ? If not, how would one go with implementing this kind of behavior ?

Thanks.

EDIT:

I added my test files in this Plunker: http://plnkr.co/edit/jIdnu68ZDMDSFJkomN3Y

First, select a hero, and click "view details", this will make an http.get request to the in-memory server to get the Hero.

Second, click on "Give sword", this will add a Weapon to the selected user. For testing purposes, instead of using the already-loaded user, I request the same one using http.get again.

When I change the name in the textbox, the name of the second instance isn't updated.

You have to imagine that I can't use the current instance of hero for whatever reasons, I want to request it again from the server.

like image 807
Growiel Avatar asked Feb 15 '16 08:02

Growiel


1 Answers

You can share a service between components.

@Injectable()
export class SharedService {
  someField:string;
}

@Component({selector: 'parent-cmp', providers [SharedService], ...)
export class ParentCmp {
  constructor(private model:SharedServicee) {
  }
}

@Component({selector: 'child-cmp', 
   // don't add it to providers here so it gets the same instance 
   // the parent got
   /*providers [SharedService] */, ...)
export class ChildCmp {
  constructor(private model:SharedServicee) {
  }
}

When one component changes a field in the service, the other service they are visible in the other component as well.

You can use Observable or EventEmitter to notify interested parties about changes or other events.

like image 61
Günter Zöchbauer Avatar answered Oct 14 '22 12:10

Günter Zöchbauer