【问题标题】:Example of injecting services in Angular 1.5 components在 Angular 1.5 组件中注入服务的示例
【发布时间】:2016-08-08 02:45:44
【问题描述】:

任何人都可以举一个使用 Angular 1.5 组件的服务的例子吗?

我正在尝试在 Angular 1.5 组件中注入服务,但它不起作用。

我有一个像这样的登录组件:

class Login {
    constructor($scope, $reactive, $state, myService) {
        console.log(myService.somevariable); //doesn't work
    }
}

// create a module
export default angular.module(name, [
    angularMeteor
]).component(name, {
    templateUrl: 'imports/ui/components/${name}/${name}.html',
    controllerAs: name,
    controller: Login
});

我的服务如下所示:

angular.module(name).service("myService", function () {
    this.somevariable = 'somevalue';
});

我似乎无法在组件中注入服务。我做错了什么?

解决方案:

在sebenalern 的帮助下,我成功了。

我需要一项服务来使用正则表达式验证电子邮件地址。我是这样做的:

import angular from 'angular';
import angularMeteor from 'angular-meteor';
class Validator { 
    validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }
}

const name = 'validator';

// create a module
export default angular.module(name, [
    angularMeteor
])

.service("Validator", Validator);

然后我像这样注入服务:

import {name as Validator} from '../../../api/services/validator'

class Login {
    constructor($scope, $reactive, $state, Validator) {
        'ngInject';
        this.$state = $state;

        $reactive(this).attach($scope);
        this.Validator = Validator;
    }

    login() {
        if(this.Validator.validateEmail(this.credentials.email)) {
            // email is valid. 
        }
    }    
}

const name = 'login';

export default angular.module(name, [
    angularMeteor,
    Validator
]).component(name, {
    templateUrl: `imports/ui/components/${name}/${name}.html`,
    controllerAs: name,
    controller:Login
})

希望这会有所帮助:)

【问题讨论】:

  • 组件是什么意思?
  • 我已经更新了问题。我正在使用 Angular 1.5 组件,但我不知道如何在其中注入 Angular 服务。由于 Angular 1.5 是新的,我也找不到任何文档。
  • 您收到错误消息了吗?
  • 我更新了我的答案。我认为它应该有所帮助。

标签: angularjs


【解决方案1】:

这是我的做法,效果很好。它适用于类。我假设您使用的是 TypeScript。

class AdminHomeService {
    consignment: IConsignment;

    get: () => IConsignment;

    constructor() {
        this.consignment = new Consignment();
        this.consignment.id = 10;
        this.consignment.customer = "Customer3";
        this.consignment.customerList = [{ id: 1, name: "Customer1" }, { id: 2, name: "Customer2" }, { id: 3, name: "Customer3" }];
        this.consignment.shipperList = [{ key: "1", value: "Shipper1" }, { key: "2", value: "Shipper2" }, { key: "3", value: "Shipper3" }];
        this.consignment.consigneeList = [{ key: "1", value: "Consignee1" }, { key: "2", value: "Consignee2" }, { key: "3", value: "Consignee3" }];
        this.consignment.billingList = [{ key: "1", value: "Billing1" }, { key: "2", value: "Billing2" }, { key: "3", value: "Billing3" }];
        this.consignment.carrierList = [{ key: "1", value: "Carrier1" }, { key: "2", value: "Carrier2" }, { key: "3", value: "Carrier3" }];

        this.get = () => {
            return this.consignment;
        }
    }
}

class AdminHomeComponentController {
    consignment: IConsignment;
    selectedCustomer: any;

    static $inject = ["adminHomeService"];

    constructor(private adminHomeService: AdminHomeService) {
        this.consignment = new Consignment();
        this.consignment = this.adminHomeService.get();

        this.selectedCustomer = {};
        this.selectedCustomer.selected = { "name": this.consignment.customer };
    }

    customerAddClick(): void {

    }
}

class AdminHomeComponent implements ng.IComponentOptions {
    bindings: any;
    controller: any;
    templateUrl: string;
    $routeConfig: angular.RouteDefinition[];

    constructor() {
        this.bindings = {
            textBinding: "@",
            dataBinding: "<",
            functionBinding: "&"
        };
        this.controller = AdminHomeComponentController;
        this.templateUrl = "templates/admin.home.html";

        //this.$routeConfig = [
        //    { path: "/admin", name: "AdminHome", component: "adminHome", useAsDefault: true }
        //];
    }
}

angular.module("adminHome", [])
    .component("adminHome", new AdminHomeComponent())
    .service("adminHomeService", AdminHomeService);

这篇文章对我帮助很大:http://almerosteyn.com/2016/02/angular15-component-typescript

【讨论】:

    【解决方案2】:

    所以我看到的一个问题是你应该在构造函数中使用关键字 this

    this.$scope = $scope;
    

    远离类和使用函数可能更容易:

    class Login {
    constructor($scope, $reactive, $state, myService) {
        console.log(myService.somevariable); //doesn't work
       }
    }
    

    变成:

    angular
    .module('name')
    .service('myService', myService);
    
    function myService () {
        this.somevariable = 'somevalue';
    }
    

    在我看来,它看起来干净多了。关于 ES6 类的另一件事是

    ES6 类没有被提升,如果你依赖提升会破坏你的代码

    欲了解更多信息,请参阅link.

    现在这是我想出的工作代码:

    首先我们声明模块:

    angular.module('name', []);
    

    接下来我们注册我们的服务,然后创建服务定义:

    angular
       .module('name')
       .service('myService', myService);
    
    function myService () {
       this.somevariable = 'somevalue';
    }
    

    接下来,我们对控制器执行相同的过程,并将 $scope 和我们的服务注入其中。

    angular
       .module('name')
       .controller('Login', Login);
    
    function Login($scope, myService) {
        $scope.someVar = myService.somevariable;
    }
    

    最后我注册了我们的组件:

    angular
       .module('name')
       .component('my-html', {
       templateUrl: 'my-html.html',
       controller: Login
    });
    

    这就是 javascript 方面的内容。

    这是我的html代码:

    <!DOCTYPE html>
    <html lang="en-us" ng-app='name'>
      <head>
          <script src="//code.angularjs.org/1.5.0-rc.1/angular.js"></script>
          <script src="controller.js"></script>
      </head>
      <body >
          <h ng-controller="Login">{{ someVar }}</h>
      </body>
    </html>
    

    希望对你有帮助!!

    【讨论】:

    • 在 Angular 1.5 中似乎不起作用。我已经更新了这个问题。我收到一个错误Error: myService is not defined。
    • 在您的帮助下,我能够让我的代码正常工作,但方式略有不同。我已经发布了我的解决方案并接受了您的回答。谢谢!
    猜你喜欢
    • 2018-05-20
    • 2016-10-25
    • 2016-10-27
    • 2016-09-15
    • 2016-09-10
    • 2015-09-05
    • 2018-11-07
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多