且构网

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

Angular2 中的工厂相当于什么?

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

工厂、服务、常量和值都在 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;
    })
  }
}