M
M
markmariner2016-10-26 12:05:29
Angular
markmariner, 2016-10-26 12:05:29

How to change data inside Angular 1.5 Component via external Service?

I am writing an application using Angular 1.5 components. The data is passed to the component from the outside through the resolve parameter, so I can display data from different sources in the same component. But I don't understand how I should proceed to change this data inside the component.
Let's say I have a User service that works with users via an API. When the state (and, accordingly, the component) is loaded, I call the Users.get () method, get the user data and pass it inside the component. For routing I use UI Router. For example:

//...
$stateProvider
      .state('users', {
        url: '/users',
        component: 'formPage',
        resolve: {
          values: function(Users) {
            return Users.get();
          });
//...

// Внутри компонента formPage
//...
component('formPage', {
  bindings: {
    values: '<'
  },
//...

I'm getting this data, all is well. But in the component template there is a form in which you can change the data. When saving this data, I want to call the Users.update () method, with which they will be transferred to the server. But the component knows nothing about the Users service! And doesn't have to know to be independent of the dataset.
How can I tell this state to use a specific Users.update() method to change the data? And how do I call this data-modifying method inside the component?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
markmariner, 2016-10-27
@markmariner

On stackoverflow.com they answered me :

resolve: {
  values: function(Users) {
    return Users.get();
  },
  onUpdate: function(){
    return Users.update.bind(Users);
  }
);

bindings: {
    values: '<',
    onUpdate: '<'
},

And you can call the function like this: $ctrl.onUpdate(data).then(...
This really works as it should.

N
Nicholas, 2016-10-26
@healqq

It's a little strange that the component doesn't need to know about the service to send data.
You can push the action through component bindings {action: '&'}if you plan to use this form with different data submission services.
But it's certainly very strange :)

L
lega, 2016-10-26
@lega

If the component is not tied to any data service, then communication can be done through properties from the parent component (application / controller).

_
_ _, 2016-10-26
@AMar4enko

В ангуляре нормально, если компонент знает о сервисе - он же не знает о его конкретной реализации, а получает его через DI. Поэтому tight coupling тут нет, можно тестировать независимо.
Так что не придумывайте себе проблем на ровном месте.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question