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

查看:105
本文介绍了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天全站免登陆