gpt4 book ai didi

angularjs - 什么相当于 Angular2 中的工厂?

转载 作者:太空狗 更新时间:2023-10-29 17:00:27 25 4
gpt4 key购买 nike

所以我习惯在 Angular 中使用工厂和服务。

我正在通读 Angular2 文档,但没有看到任何与工厂等效的东西。 Angular2 的等价物是什么?

最佳答案

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

  • 组件
  • 依赖注入(inject)
  • 绑定(bind)

服务、工厂、提供者和常量的概念在 Angular 1 中受到批评。很难在两者之间做出选择。删除它们可以简化一些事情。

在最初的 Angular 中,你会像这样定义一个服务

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 语法使代码更易读和更容易理解。

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

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 中的样子

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;
})
}
}

关于angularjs - 什么相当于 Angular2 中的工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com