Angular Service创建的函数需要此关键字 [英] Angular Service created function needs this keyword

查看:61
本文介绍了Angular Service创建的函数需要此关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管问题更多,我认为javascript类型的问题比Angular问题更重要,但是我正在创建一个服务,我可以这样称呼它

While the question is more I suppose javascript type question more so than an Angular question, I was creating a service in which I would call it like this

// controller injects activityApi , then service function call is made
var activities = activityApi.getActivityById(1122);

如果我没有在函数名称前放置"this"关键字,则会出现错误1.为什么我需要这个".
2.还有什么其他选择?(我正试图养成不使用 function blah(){...}

I get an error if I do not put "this" keyword in front of function name 1. Why do I need "this."
2. What other alternatives? ( I am trying to get into the habit of not doing old school javascript with function blah() { ... }

this.getActivityById = function(id) {
        $http.get('/Umbraco/Api/ActivityApi/GetActivity').
            success(function (data, status, headers, config) {
            console.log(data);
            return data;
            }).
       error(function (data, status, headers, config) {
           // log error
       });
    };

推荐答案

如果要编写工厂,请使用工厂内部的对象,然后将所有调用都放入其中.就像

If you are writing a factory make use of an object inside the factory ,and put all your calls into it.like

(function() {
    'use strict';

    angular
        .module('app')
        .factory('activityApi', activityApi);

    activityApi.$inject = ['$http'];

    function activityApi($http) {
        var service = {
              getActivityById : getActivityById ,
        };
        return service;


     function getActivityById (id) {
        $http.get('/Umbraco/Api/ActivityApi/GetActivity').
          success(function (data, status, headers, config) {
           console.log(data);
           return data;
        }).
       error(function (data, status, headers, config) {
          // log error
       });
    };

    };
})();

在这里,您将返回可以使用调用函数的工厂对象.

here you are returning factory object in which calling function is available.

在这里您可以将工厂函数调用为

Here you can call the factory function as

var activities = activityApi.getActivityById(1122);

这篇关于Angular Service创建的函数需要此关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆