簡體   English   中英

在控制器中調用AngularJS服務函數時出錯?

[英]Error while calling AngularJS service function in controller?

我編寫了一項服務,該服務從一個控制器獲取數據並將其發送到另一個控制器。 該控制器指向不同的模塊。 現在,當我從兩個控制器調用服務函數時,它會引發一些錯誤。

angular.js:13920 ReferenceError:Object.dataservice中未定義addData

這是我在pages.module.js中的服務

(function ()
{
    'use strict';

    angular
        .module('app.pages', [
            'app.pages.auth.login',
            'app.pages.auth.login-v2',
            'app.pages.auth.register',
            'app.pages.auth.register-v2',
            'app.pages.auth.verify-mobile',
            'app.pages.auth.reset-password',
            'app.pages.auth.lock',
            'app.pages.coming-soon',
            'app.pages.error-404',
            'app.pages.error-500',
            'app.pages.invoice',
            'app.pages.maintenance',
            'app.pages.profile',
            'app.pages.search',
            'app.pages.timeline'
        ])
        .config(config)
        .factory('dataservice', dataservice);

    /** @ngInject */
    function config(msNavigationServiceProvider)
    {
        // Navigation
        msNavigationServiceProvider.saveItem('pages', {
            title : 'PAGES',
            group : true,
            weight: 2
        });
    }

     function dataservice(){

        var sendarr = [];

        this.addData = function(newObj) {
            sendarr.push(newObj);
        };

        this.getData = function(){
            return sendarr;
        };

        return {
            addData: addData,
            getData: getData
        };

    }
})();

這是第一個控制器login.controller.js

(function ()
{
    'use strict';

    angular
        .module('app.pages.auth.login')
        .controller('LoginController', LoginController);

    /** @ngInject */
    LoginController.$inject = ['dataservice'];
    function LoginController(msApi,$state,dataservice)
    {
        // Data
        var vm = this;

        vm.login = login;
        vm.startApp = startApp;
        vm.fbLogin = fbLogin;
        var auth2;
        // Methods
        function fbLogin(){
            FB.login(function(response){
                if(response.status=='connected'){
                    testAPI();
                }
                else if(response.status == 'not_authorized'){
                    console.log('error');
                }
                else{
                    console.log('please log in');
                }
            });
        }

        function testAPI() {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                console.log('Successful login for: ' + response.name);

            });
        }

        function startApp(){
            gapi.load('auth2', function(){
            // Retrieve the singleton for the GoogleAuth library and set up the client.
                auth2 = gapi.auth2.init({
                client_id: '990822731291-21sdd22ujqc78l1q2i2lmf5hfe5satj1.apps.googleusercontent.com',
                cookiepolicy: 'single_host_origin',
                fetch_basic_profile: 'true',
                // Request scopes in addition to 'profile' and 'email'
                //scope: 'additional_scope'
                });
                attachSignin(document.getElementById('customGoogleBtn'));
             });
        }

        function attachSignin(element) {
            auth2.attachClickHandler(element, {},
                function(googleUser) {
                    var profile = googleUser.getBasicProfile();
                    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
                    console.log('Name: ' + profile.getName());
                    console.log('Image URL: ' + profile.getImageUrl());
                    console.log('Email: ' + profile.getEmail());
                    var pushData = [profile.getId(), profile.getName(), profile.getEmail()];
                    console.log(pushData);
                    dataservice.addData(pushData);
                    $state.go('app.pages_auth_verify-mobile')
                }, 
                function(error) {
                    alert(JSON.stringify(error, undefined, 2));
            });
        }

        function login(){
            var jsonData = {"mobile":vm.form.mobile};
            msApi.request('login.credentials@save',jsonData,
                // SUCCESS
                function (response)
                {
                   console.log(response.error);
                    if(response.error == 1){
                        vm.form.mobileErrorFlag = true;
                    }
                    if(response.error == 0){
                        vm.form.mobileErrorFlag = false;
                    }
                },
                // ERROR
                function (response)
                {
                    alert(JSON.stringify(response));
                }
            )
        }



    }
})();

這是第二個控制器verify-mobile.controller.js

(function ()
{
    'use strict';

    angular
        .module('app.pages.auth.verify-mobile')
        .controller('VerifyMobileController', VerifyMobileController);

    /** @ngInject */
    function VerifyMobileController(dataservice)
    {
        var data = dataservice.getData();

        alert(data);
    }
})();

你有方法為this.addDatathis.getData在你dataservice ,而你正在訪問同一個無this的回報。 這就是為什么您會收到此錯誤。

您無需在factory service使用this即可刪除以下內容。

function dataservice(){

        var sendarr = [];

        var addData = function(newObj) {
            sendarr.push(newObj);
        };

        var getData = function(){
            return sendarr;
        };

        return {
            addData: addData,
            getData: getData
        };

    }

暫無
暫無

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

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