Home  >  Article  >  Web Front-end  >  What are services in AngularJS? Introduction to how to use angularjs

What are services in AngularJS? Introduction to how to use angularjs

寻∝梦
寻∝梦Original
2018-09-08 15:17:571255browse

This article mainly introduces the services in angularjs, as well as the details of dependencies in angularjs. Let’s take a look at this article now

Description

Translator’s Note: I saw a very good article, if you have If you are interested, you can check out: Promises and Javascript Asynchronous Programming, which covers Promises specifications and usage scenarios. The benefits are explained very thoroughly, and I personally find it simple and easy to understand.

Since it is used to handle asynchronous programming, there are two main types in browser-side JS: setTimeout and Ajax requests. The use of promises is very similar to the success and failure callbacks of Ajax requests.

This promise/deferred implementation is inspired by Kris Kowal's Q CommonJS Promise recommendation document to use promises as an interface for interacting with asynchronous execution operation (action) result objects, in the specified It may or may not be completed within the time (such as timeout, error, interception, etc.).

From an error handling perspective, delay (deferred ) and promise (promise ) APIs are for asynchronous programming, and ## for synchronous programming # try, catch, and throw have similar effects.

// 为了演示的目的,此处我们假设 `$q`, `scope` 以及 `okToGreet` 引用 在当前执行环境中可用
// (比如他们已经被注入,或者被当做参数传进来了).
 
function asyncGreet(name) {
  var deferred = $q.defer();
 
  setTimeout(function() {
    // 因为此function 在未来的事件循环中异步执行,
    // 我们需要把代码包装到到一个 $apply 调用中,以便正确的观察到 model 的改变
    scope.$apply(function() {
      deferred.notify('即将问候 ' + name + '.');
 
      if (okToGreet(name)) {
        deferred.resolve('你好, ' + name + '!');
      } else {
        deferred.reject('拒绝问候 ' + name + ' .');
      }
    });
  }, 1000);
 
  return deferred.promise;
}
 
var promise = asyncGreet('小漠漠');
promise.then(function(greeting) {
  alert('成功: ' + greeting);
}, function(reason) {
  alert('失败鸟: ' + reason);
}, function(update) {
  alert('收到通知: ' + update);
});
The effect of introducing this additional complexity may not be apparent at first . The benefits can be seen when making promises with promise and deferred APIs, please refer to: https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md

In addition, the promise API allows those in traditional callbacks (CPS) method is a difficult combination to achieve. For more information, please consult
QDocumentation, especially the section on Merging Serial and Parallel.

Deferred Interface | Deferred API

A new deffered instance can be constructed by calling $q.defer().

The deffered object is used to associate a Promise instance with the API that marks the task status (successful or unsuccessful execution).

Methods of deffered objects

  • resolve(value) ——Pass in value to resolve the derived promise. If value is a rejection object (rejection) constructed through $q.reject, the promise will be rejected.

  • reject(reason) ——Reject the derived promise and provide the reason. This is equivalent to passing the rejection object (rejection) constructed through $q.reject as a parameter to resolve.

  • notify(value) - Provides status updates during promise execution. This may be called multiple times before the promise is resolved or rejected.

deffered Object properties

promise – {Promise} —— Promise associated with deferred object.

Promise Interface | Promise API

When a deferred instance is created, a new promise object will be created, and the reference can be obtained through

deferred.promise. The purpose of the promise object is to allow the interested part to obtain its execution results when the deferred task is completed.

Methods of the promise object

  • then(successCallback, errorCallback, notifyCallback) ——No matter whether the promise is processed or rejected, once the result is available, then The success/error callback function will be called asynchronously as soon as the result is available. The callback function is called passing a single argument: the result or the reason for rejection. Additionally, the notify callback may be called zero to more times to provide an indication of progress before the promise is resolved or rejected.

This method returns a new promise object, which can be resolved or rejected based on the return values ​​of successCallback and errorCallback. It also notifies via the return value of the notifyCallback method. A promise cannot be resolved or rejected from the notifyCallback method.


  • catch(errorCallback) —— shortcut for promise.then(null, errorCallback)

  • finally(callback) - allows you to observe whether a promise is executed or rejected, but does so without modifying the final value. This can be used to do some work of releasing resources or cleaning up unused objects, regardless of whether the promise is rejected or resolved. For more information, please refer to the full document specification.

  • ## Because in the ES3 version of JavaScript finally is a reserved word keyword and cannot be used as a property name, in order to adapt to IE8, you need to use promise['finally'](callback) to call this method.


promise chain | Chaining promises

Because calling the then method of a promise returns a new derived promise instance, it is also easy to build a promise chain:

promiseB = promiseA.then(function(result) {
  return result + 1;
});
 
// promiseB 将会在处理完 promiseA 之后立刻被处理,
// 并且其  value值是promiseA的结果增加1

我们可以创建任意长度的promise链;因为一个promise可以被另一个promises处理(进一步推迟解决完成时间),所以在promise链上的任意一点进行 暂停/推迟解决 都是可行的。 这使得实现功能强大的APIs 成为现实,例如  $http 的响应拦截器。

Kris Kowal's Q 与 $q 之间的区别

主要区别有两点:

  • Angular中的$q 集成了 ng.$rootScope.Scope  Scope模型观察机制,这意味着对models 的解决或拒绝速度将会更快,避免不必要的浏览器重绘(会导致UI闪烁)。

  • Q 比 $q拥有更多的功能特性,但带来的是代码字节数的增加。 $q 很轻量级,但包含了一般异步任务所需的所有重要功能。

     测试

it('should simulate promise', inject(function($q, $rootScope) {
  var deferred = $q.defer();
  var promise = deferred.promise;
  var resolvedValue;
 
  promise.then(function(value) { resolvedValue = value; });
  expect(resolvedValue).toBeUndefined();
 
  // 模拟 promise 的 resolving
  deferred.resolve(123);
  // 注意 'then' function 不是同步调用的.
  // 因为我们想要  promise API 一直是异步的(async),
  // 不管是在同步调用还是异步调用中都是如此.
  expect(resolvedValue).toBeUndefined();
 
  // 使用 $apply()将 promise resolution 传递到 'then' functions .
  $rootScope.$apply();
  expect(resolvedValue).toEqual(123);
}));

依赖关系 | Dependencies

$rootScope 

方法 | Methods

all(promises)

结合多个promises为单个promise,在所有输入的promise都处理之后,组合之后的promise才会处理完成。

  • 参数: promises

  • 类型: Array./Object.

  • 描述: promises的数组或者引用

  • 返回: Promise 返回单个的 promise,将与一个数组解决/散列值, 每个值对应于在相同的索引/关键的承诺 承诺 /散列数组。 如果任何承诺解决排斥,这产生的承诺将被拒绝 拒绝相同的值。(想看更多就到PHP中文网AngularJS开发手册中学习)

defer()

创建一个 递延 对象代表一个将来完成任务。

  • 返回  Deferred 返回一个新实例的Deferred。

reject(reason)

创建一个指定拒绝原因的promise. 此api应该用于在一个promises链中进行拒绝。 如果你正在处理promise 链中的最后一个promise,你不需要担心。

把  deferreds/promises 与我们熟悉的的 try/catch/throw行为进行对比,可以认为 reject 相当于 JavaScript 中的throw 关键字。 这也意味着如果你通过一个 promise 的 error回调,  “catch”了一个错误 ,你想要指明当前的承诺已经执行出错了,就必须重新抛出一个“附带了错误信息,拒绝通过的reject” 。

promiseB = promiseA.then(function(result) {
  // success: 此处可以执行某些操作,然后直接使用原有的result,
  // 或者对result进行操作,来处理接下来的promiseB
  return result;
}, function(reason) {
  // error: handle the error if possible and
  //        resolve promiseB with newPromiseOrValue,
  //        否则转向拒绝 promiseB 的分支
  if (canHandle(reason)) {
   // 处理错误和恢复
   return newPromiseOrValue;
  }
  return $q.reject(reason);
});
  • 参数: reason

  • 类型: *

  • 描述: Constant, message, exception 或代表拒绝原因的 object。

  • 返回: Promise    返回一个promise ,已经因为 reason 而被拒绝了 。

when(value)

将一个对象(可能是value 或  [第三方]then-able promise) 包装为一个 $q promise。 这在你不确定所处理的对象是否是一个promise 时是很有用的,有可能该对象来自于一个不被信任的源头。

  • 参数: value

  • 类型: *

  • 描述: promise 的值

  • 返回 Promise    根据传入的值/或promise 返回一个包装后的 promise

本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。

The above is the detailed content of What are services in AngularJS? Introduction to how to use angularjs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn