angular 组件、服务和控制器如何工作

how angular component, service and controller works

我是 angular 的新手,正在尝试了解服务、组件和控制器的工作原理。

假设我有以下内容:

服务文件:products.service.js

 'use strict';

 angular.module('myApp.products')
 .factory('ProductService', function () {

     var products = [
            {_id: 1, title: 'Product 1', price: 123.45, quantity:10, description:'Some description 1'},
            {_id: 2, title: 'Product 2', price: 123.45, quantity:10, description:'Some description 2'},
            {_id: 3, title: 'Product 3', price: 123.45, quantity:10, description:'Some description 3'},
            {_id: 4, title: 'Product 4', price: 123.45, quantity:10, description:'Some description 4'},
            {_id: 5, title: 'Product 5', price: 123.45, quantity:10, description:'Some description 5'}
     ];

     return {
          alllProducts: function () {
              return products;
          }
     };
});

控制器文件:products.controller.js

 'use strict';
 (function(){

          class ProductsComponent {
               constructor() {
                   // how should i connect them here like below?
                   // this.products = ProductService.allProducts();
               }
          }

          angular.module('myApp')
               .component('products', {
                   templateUrl: 'app/products/products.html',
                    controller: ProductsComponent
               });

 })();

我正在使用生成器-angular-fullstack。如何连接控制器构造函数中的所有产品并在模板中显示它们?

谢谢

你很接近,你只需要将 ProductService 注入构造函数:

class ProductsComponent {
    constructor(ProductService) {
        this.products = ProductService.allProducts();
    }
}

google 上有数百种关于控制器、服务、指令的解释。其中许多将使用 ES5 语法。组件是一种更具体的指令类型 - 请参阅 the docs

简而言之,虽然服务控制您的应用程序数据,但控制器的唯一职责是将该数据公开给视图。每当 angular 实例化控制器时,它都会为其提供一个由 this 引用的范围(至少,一旦控制器完成实例化)。

该组件是您视图的一部分。您使用非驼峰大小写版本,此处 html 视图模板中的 <products></product>,angular 将其替换为您的模板,并将 controller/controller 范围附加到该部分的观点。您可以使用 products.html 模板中的产品(例如使用 <div ng-repeat="product in products>{{product.title}}></div>")。