共享服务将变量返回为undefined angularjs

时间:2017-04-04 23:41:33

标签: angularjs asp.net-core-mvc

我正在尝试使用服务在两个控制器之间共享变量。 下面是我的代码:

(function() {
'use strict';

angular.module('simple.module')
    .service("projectService",
        function($http, $httpParamSerializerJQLike) {
            var projectId;
            //var service = {};
            //return {
            this.getProjects = function() {
                return $http.get("/project/getprojects");
            };
            this.favourites = function(id) {
                return $http({
                    method: "POST",
                    url: "/project/markasfavourite",
                    headers: { 'Content-Type': "application/x-www-form-urlencoded" },
                    data: id
                });
            };
            this.setProjectId = function(id) {
                projectId = id;
            };
            this.getProjectId = function() {
                return projectId; <----this is returned as undefined
            };
           // return service;
            // };
        });})();

我是棱角分明的新手,并且已经投入了大量时间让它发挥作用。最初我是在使用工厂,后来改用服务并做了大量的工作: Why does this AngularJs Service with variable object name return an undefined object? Value of variable becomes undefined after calling data service Variable undefined in Service, after saving a value in it (AngularJS) 还有很多其他的地方,所以在这个问题被标记为重复并关闭之前,请有人指出我错过了什么?为什么projectId总是以undefined的形式返回? 谢谢。

编辑:控制器

 function projectsController(projectService, $window) {
    var vm = this;vm.edit = function (id) {
        projectService.setProjectId(id);
        $window.location.pathname = '/project/create/'+id;
    };}
function createController(createService,projectService, $window) { 
    var vm = this;
    debugger;
    var projectId = projectService.getProjectId();}

0 个答案:

没有答案