簡體   English   中英

Angular2中的工廠相當於什么?

[英]What is the equivalent of a factory in Angular2?

因此,我習慣於在Angular中使用工廠和服務。

我正在閱讀Angular2文檔,但看不到任何等效的工廠。 Angular2的等效項是什么?

工廠,服務,常量和值都在Angular2中消失了。 Angular2與經典Angular有根本性和根本性的不同。 在Angular2中,核心概念是

  • 組件
  • 依賴注入
  • 捆綁

服務,工廠,提供者和常量的概念在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類是對基於原型的OO模式的簡單補充。 具有單個方便的聲明形式使類模式更易於使用,並鼓勵了互操作性。 類支持基於原型的繼承,超級調用,實例以及靜態方法和構造函數。

這是相同的代碼在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;
    })
  }
}

@理查德·漢密爾頓(Richard Hamilton)的回答令人贊賞,此外,還有幾點需要注意。

對於Factory,Service等,在Angular2中我們有service(或共享服務) 我們必須使我們的服務可Injectable才能使用。

注意:此代碼屬於beta版本,而不是RC。

import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
import {Router} from 'angular2/router';
import {Http} from 'angular2/http';

export interface ImyInterface {
   show:boolean;
}

@Injectable()      <---------------------------- Very Important
export class sharedService {  <----------------- Service Name
  showhide:ImyInterface={show:true};

  constructor(http:Http;router:Router)
  {
    this.http=http;
  }     
  change(){
        this.showhide.show=!this.showhide.show;
  }
} 

如果我想在我的應用程序中的任何地方使用它,那么我必須將此服務注入到這樣的引導函數中,

bootstrap(App, [HTTP_PROVIDERS,sharedService    <--------Name Injection
      ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)
]);

這樣,它將創建您的服務的單個實例。 如果您不希望使用單個實例,則可以做的是-您可以在@component裝飾器中使用Providers:[sharedService]元數據。

然后,在這樣的組件之一中使用它,

export class TheContent {
  constructor(private ss: sharedService) {  <--------Injection dependency of your newly created service
    console.log("content started");
  }
  showhide() {
    this.ss.change();  <----- usage
  }
}

在這里檢查工作示例

我不知道在Angular1中確切執行什么工廠,但是在Angular2中有useFactory

{ 
  provide: SomeClass, 
  useFactory: (dep1, dep2) => (x) => new SomeClassImpl(x, dep1, dep2),
  deps: [Dep1, Dep2]
}

如果默認值不符合您的需求,則提供您自己的實例構造邏輯。

您還可以自己注入工廠來創建新實例:

/* deprecated or removed depending on the Angular version you are using */
provide(SomeClass, {
    useFactory: (dep1, dep2) => {
        (x) => new SomeClassImpl(x, dep1, dep2), 
    },
    deps: [Dep1, Dep2]
})
constructor(@Inject(SomeClass) someClassFactory: any) {
  let newSomeClass = someClassFactory(1);
}

參數x必須具有類型分配,否則angular不知道如何處理它。

class SomeClassImpl {
  constructor(x: number, dep1: Dep1, dep2: Dep2){}
}

如果在某個組件中需要服務的新實例,則需要在該組件中提供它,如下所示:

@Component({
  selector:    'hero-list',
  templateUrl: './hero-list.component.html',
  providers:  [ HeroService ]
})

這將像工廠一樣生成HereService的新實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM