Angular2 中的工厂相当于什么? [英] What is the equivalent of a factory in Angular2?

查看:26
本文介绍了Angular2 中的工厂相当于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我习惯使用工厂&Angular 中的服务.

So I am used to using factories & services in Angular.

我正在阅读 Angular2 文档,但我没有看到任何等效的工厂.Angular2 的等价物是什么?

I am reading through the Angular2 docs and I don't see any equivalent of a factory. What is the equivalent for Angular2?

推荐答案

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

这篇关于Angular2 中的工厂相当于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆