且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular2中的工厂相当于什么?

更新时间:2022-01-25 05:00:24

在Angular2中,工厂,服务,常量和值都消失了. Angular2与经典Angular有根本性和根本性的不同.在Angular2中,核心概念是

Factories, services, constants and values are all gone in Angular2. Angular2 is radically and fundamentally different from the classic Angular. In Angular2, the core concepts are

  • 组件
  • 依赖注入
  • 绑定

服务,工厂,提供者和常量的概念在Angular 1中受到批评.很难在两者之间进行选择.删除它们会简化一些事情.

The idea of services, factories, providers and constants has been criticized in Angular 1. It was difficult to choose between one. Removing them simplifies things a bit.

在原始的Angular中,您将像这样定义服务

In the original Angular, you would define a service like so

app.service('BookService', ['$http', '$q', BookService]);
function BookService($http, $q){
  var self = this;
  var cachedBooks;
  self.getBooks = function(){
    if (cachedBooks) {
      return $q.when(cachedBooks);
    }
    return $http.get('/books').then(function(response){
      cachedBooks = response.data.books;
      return cachedBooks;
    })
  }
}

Angular2大大利用了ES6语法,使代码更具可读性和易懂性.

Angular2 significantly leverages ES6 syntax to make the code more readable and easier to understand.

ES6中的一个新关键字是class,可以将其视为一项服务.

One new keyword in ES6 is class, which can be thought of as a service.

ES6类是基于原型的OO模式的简单糖.具有单个方便的声明形式使类模式更易于使用,并鼓励了互操作性.类支持基于原型的继承,超级调用,实例以及静态方法和构造函数.

ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

这是相同的代码在Angular2中的外观

Here's how that same code might look in Angular2

import {HttpService, Promise}  from '../Angular/Angular2';
export class BookService{
    $http, $q, cachedBooks;
    constructor($http: HttpService, $q: Promise) {
        this.$http = $http;
        this.$q = $q
    }
    getBooks() {
    if (this.cachedBooks) {
        return this.$q.when(this.cachedBooks);
    }
    return this.$http.get('/books').then(function(data) {
        this.cachedBooks = data.books;
        return this.cachedBooks;
    })
  }
}