AngularJs中的类操作和实例操作之间有什么区别?

时间:2022-02-16 13:21:36

From the docs:

来自文档:

Class actions return empty instance (with additional properties below). Instance actions return promise of the action

类操作返回空实例(下面有其他属性)。实例操作返回操作的承诺

The documentations however doesn't clearly differentiate between Class actions and Instance actions. Could you please point out differences with a good example if possible?

但是,文档没有明确区分类操作和实例操作。如果可能的话,你能指出一个很好的例子吗?

1 个解决方案

#1


11  

When you create a new resource type, you supply it a list of actions that can be performed. By default, these are get, save, query, delete, and remove (I think remove is just an alias of delete). You can add your own, as it says in the docs.

创建新资源类型时,可以为其提供可执行的操作列表。默认情况下,这些是获取,保存,查询,删除和删除(我认为删除只是删除的别名)。您可以添加自己的文件,如文档中所述。

The thing about class vs instance is in regard to something it does for convenience of use. "Class actions" refers to calling the action off the resource class that you create itself, kinda like static or shared methods in some other languages. This is useful as an entry point for getting, querying, or saving an instance of your resource when you don't already have the instance. get and query are the clearest example of this. If you have a Car resource, and you need to retrieve it, where do you start? With a class action, of course, such as get.

关于类vs实例的事情是关于它为了方便使用而做的事情。 “类操作”是指从您自己创建的资源类调用操作,有点像其他语言中的静态或共享方法。当您还没有实例时,这可用作获取,查询或保存资源实例的入口点。获取和查询是最明显的例子。如果您有汽车资源,并且需要检索它,那么您从哪里开始?当然,有了集体诉讼,比如获得。

Now, when your resource class retrieves an existing instance, or you create a new instance, $resource will extend your instance with the actions defined for your resource, but prefix them with a $ so they don't collide with fields on your resource. These are your instance actions. The difference between instance and class, is instance is done in the context of the current instance. So if you get an instance, but then call $save or $delete on that instance, it will save or delete that instance specifically. Instance actions are there simply for convenience.

现在,当您的资源类检索现有实例,或者您创建一个新实例时,$ resource将使用为您的资源定义的操作扩展您的实例,但为它们添加$前缀,以便它们不会与您资源上的字段发生冲突。这些是您的实例操作。实例和类之间的区别是实例是在当前实例的上下文中完成的。因此,如果您获得一个实例,然后在该实例上调用$ save或$ delete,它将专门保存或删除该实例。实例操作只是为了方便起见。

So they are pretty much the same, the difference is the context in which they are being used.

所以它们几乎相同,不同之处在于它们的使用环境。

function($resource) {     

   // first let's define a new resource for car, where all cars have an id field
   // calling $resource will create a new resource class that can be used to 
   // create, retrieve, update, or delete instances
   // this is usually done as a service and injected into controllers as needed.
   var Car = $resource('/api/car/:id', {id: '@id'});

   // the car class we just created has some class actions that can help you query for or get car instances
   // let's create a new instance of a car and save it
   var newCar = new Car({make: 'Toyota', model: 'Prius'});
   // the prototype of Car includes the instance action versions of the actions defined for the resource. below, $save is your instance action
   newCar.$save(); // server will respond with the object after it's saved, so we can now access the id. let's say the id it returned is 24, we'll reference this value later.


   // now, let's imagine some time later we want to retrieve the car and update it
   // Car.get is a class action that requests the resource from the server, parses the JSON into an object, and merges it with the Car instance prototype so you have your instance actions
   // let's get the car we created previously.
   // remember, this is done asynchronously, so we will do our work in a success handler that we provide to get
   Car.get({id: 24}, function(myCar) {
       // let's update the car now that we have it. let's set the year of the model and the color
       myCar.year = 2004;
       myCar.color = 'white';

       // now, let's save our changes by calling the instance action $save
       myCar.$save();
   });


   // now, let's query for all cars and get an array back
   // query is a class function that expects an array of your resource to be returned
   Car.query(function(cars) {
        // trivial example, we're just going to enumerate the cars we found and log some info about them
       for(var i = 0; i < cars.length; i++)
          console.log('Found ' + cars[0].color + ' ' cars[0].year + ' ' + cars[0].make + ' ' + cars[0].model);
   });


   // ok, let's delete the car we created earlier. use the class action delete
   Car.delete({id: 24});
}

You can technically call any actions either as a class or as an instance, but it will become obvious that some are awkward to use as instance actions and vise versa. For example, while you technically can use query as an instance action, you wouldn't do that in practice because it's extra work and it's awkward (you'd have to do new Car().$query(). That's silly. Car.query() is easier and makes more sense). So, the usage in my example above represents your normal usage.

从技术上讲,您可以将任何操作调用为类或实例,但很明显,有些操作很难用作实例操作,反之亦然。例如,虽然你在技术上可以使用查询作为实例操作,但是你不会在实践中这样做,因为它是额外的工作并且它很笨拙(你必须做新的Car()。$ query()。这太傻了。 .query()更容易,更有意义。因此,上面示例中的用法表示您的正常用法。


Update:

save vs $save

保存vs $ save

$save is similar to save, but it assumes the data you want to submit during save is itself, since $save is an instance action. It is particularly useful because after the response is received, it'll update itself with the object returned by your HTTP endpoint. So if your service saves the object with some additional values populated on the server side, such as an ID, then sends the object back as JSON, $save will update the instance with the returned JSON object.

$ save与save类似,但它假设您要在save期间提交的数据本身,因为$ save是一个实例操作。它特别有用,因为在收到响应后,它将使用HTTP端点返回的对象更新自身。因此,如果您的服务使用服务器端填充的一些其他值(例如ID)保存对象,则将对象作为JSON发回,$ save将使用返回的JSON对象更新实例。

 var car = new Car({make: 'Toyota', model: 'Prius'});
 // at this point there is no id property, only make and model
 car.$save(function() {
    // angular is async, so we need a success handler to continue the explanation

    // assuming your server assigned an ID and sent the resulting object back as JSON, you can now access id off the original object
    console.log(car.id); // has a value now
 });

You could do something similar with the class method, but it's awkward, particularly if other code in your controller needs to reference the car as you are working on it

您可以使用类方法执行类似操作,但它很笨拙,特别是如果您正在处理它时控制器中的其他代码需要引用汽车

 Car.save({make: 'Toyota', model: 'Prius'}, function(car) {
       // ok, we have an ID now
       console.log(car.id);
 });

or

 var car = new Car({...});
 Car.save(car, function(newCar) {
      car = newCar; // wut? that's awkward
 });

save could be useful during instances where you are quickly saving a small object, or are performing a sort of "fire and forget". Anyways, I rarely use save myself.

在快速保存小对象或执行某种“火灾和忘记”的情况下,保存可能很有用。无论如何,我很少使用保存自己。

#1


11  

When you create a new resource type, you supply it a list of actions that can be performed. By default, these are get, save, query, delete, and remove (I think remove is just an alias of delete). You can add your own, as it says in the docs.

创建新资源类型时,可以为其提供可执行的操作列表。默认情况下,这些是获取,保存,查询,删除和删除(我认为删除只是删除的别名)。您可以添加自己的文件,如文档中所述。

The thing about class vs instance is in regard to something it does for convenience of use. "Class actions" refers to calling the action off the resource class that you create itself, kinda like static or shared methods in some other languages. This is useful as an entry point for getting, querying, or saving an instance of your resource when you don't already have the instance. get and query are the clearest example of this. If you have a Car resource, and you need to retrieve it, where do you start? With a class action, of course, such as get.

关于类vs实例的事情是关于它为了方便使用而做的事情。 “类操作”是指从您自己创建的资源类调用操作,有点像其他语言中的静态或共享方法。当您还没有实例时,这可用作获取,查询或保存资源实例的入口点。获取和查询是最明显的例子。如果您有汽车资源,并且需要检索它,那么您从哪里开始?当然,有了集体诉讼,比如获得。

Now, when your resource class retrieves an existing instance, or you create a new instance, $resource will extend your instance with the actions defined for your resource, but prefix them with a $ so they don't collide with fields on your resource. These are your instance actions. The difference between instance and class, is instance is done in the context of the current instance. So if you get an instance, but then call $save or $delete on that instance, it will save or delete that instance specifically. Instance actions are there simply for convenience.

现在,当您的资源类检索现有实例,或者您创建一个新实例时,$ resource将使用为您的资源定义的操作扩展您的实例,但为它们添加$前缀,以便它们不会与您资源上的字段发生冲突。这些是您的实例操作。实例和类之间的区别是实例是在当前实例的上下文中完成的。因此,如果您获得一个实例,然后在该实例上调用$ save或$ delete,它将专门保存或删除该实例。实例操作只是为了方便起见。

So they are pretty much the same, the difference is the context in which they are being used.

所以它们几乎相同,不同之处在于它们的使用环境。

function($resource) {     

   // first let's define a new resource for car, where all cars have an id field
   // calling $resource will create a new resource class that can be used to 
   // create, retrieve, update, or delete instances
   // this is usually done as a service and injected into controllers as needed.
   var Car = $resource('/api/car/:id', {id: '@id'});

   // the car class we just created has some class actions that can help you query for or get car instances
   // let's create a new instance of a car and save it
   var newCar = new Car({make: 'Toyota', model: 'Prius'});
   // the prototype of Car includes the instance action versions of the actions defined for the resource. below, $save is your instance action
   newCar.$save(); // server will respond with the object after it's saved, so we can now access the id. let's say the id it returned is 24, we'll reference this value later.


   // now, let's imagine some time later we want to retrieve the car and update it
   // Car.get is a class action that requests the resource from the server, parses the JSON into an object, and merges it with the Car instance prototype so you have your instance actions
   // let's get the car we created previously.
   // remember, this is done asynchronously, so we will do our work in a success handler that we provide to get
   Car.get({id: 24}, function(myCar) {
       // let's update the car now that we have it. let's set the year of the model and the color
       myCar.year = 2004;
       myCar.color = 'white';

       // now, let's save our changes by calling the instance action $save
       myCar.$save();
   });


   // now, let's query for all cars and get an array back
   // query is a class function that expects an array of your resource to be returned
   Car.query(function(cars) {
        // trivial example, we're just going to enumerate the cars we found and log some info about them
       for(var i = 0; i < cars.length; i++)
          console.log('Found ' + cars[0].color + ' ' cars[0].year + ' ' + cars[0].make + ' ' + cars[0].model);
   });


   // ok, let's delete the car we created earlier. use the class action delete
   Car.delete({id: 24});
}

You can technically call any actions either as a class or as an instance, but it will become obvious that some are awkward to use as instance actions and vise versa. For example, while you technically can use query as an instance action, you wouldn't do that in practice because it's extra work and it's awkward (you'd have to do new Car().$query(). That's silly. Car.query() is easier and makes more sense). So, the usage in my example above represents your normal usage.

从技术上讲,您可以将任何操作调用为类或实例,但很明显,有些操作很难用作实例操作,反之亦然。例如,虽然你在技术上可以使用查询作为实例操作,但是你不会在实践中这样做,因为它是额外的工作并且它很笨拙(你必须做新的Car()。$ query()。这太傻了。 .query()更容易,更有意义。因此,上面示例中的用法表示您的正常用法。


Update:

save vs $save

保存vs $ save

$save is similar to save, but it assumes the data you want to submit during save is itself, since $save is an instance action. It is particularly useful because after the response is received, it'll update itself with the object returned by your HTTP endpoint. So if your service saves the object with some additional values populated on the server side, such as an ID, then sends the object back as JSON, $save will update the instance with the returned JSON object.

$ save与save类似,但它假设您要在save期间提交的数据本身,因为$ save是一个实例操作。它特别有用,因为在收到响应后,它将使用HTTP端点返回的对象更新自身。因此,如果您的服务使用服务器端填充的一些其他值(例如ID)保存对象,则将对象作为JSON发回,$ save将使用返回的JSON对象更新实例。

 var car = new Car({make: 'Toyota', model: 'Prius'});
 // at this point there is no id property, only make and model
 car.$save(function() {
    // angular is async, so we need a success handler to continue the explanation

    // assuming your server assigned an ID and sent the resulting object back as JSON, you can now access id off the original object
    console.log(car.id); // has a value now
 });

You could do something similar with the class method, but it's awkward, particularly if other code in your controller needs to reference the car as you are working on it

您可以使用类方法执行类似操作,但它很笨拙,特别是如果您正在处理它时控制器中的其他代码需要引用汽车

 Car.save({make: 'Toyota', model: 'Prius'}, function(car) {
       // ok, we have an ID now
       console.log(car.id);
 });

or

 var car = new Car({...});
 Car.save(car, function(newCar) {
      car = newCar; // wut? that's awkward
 });

save could be useful during instances where you are quickly saving a small object, or are performing a sort of "fire and forget". Anyways, I rarely use save myself.

在快速保存小对象或执行某种“火灾和忘记”的情况下,保存可能很有用。无论如何,我很少使用保存自己。