2015-11-19 14 views
5

私は角度が少し新しいです。私は '従業員検索'サービスモジュールを構築しました。ここにコードがあります...コントローラから角度サービスメソッドを呼び出す方法は?

// Service for employee search 
app.service('employeeSearchService', function($http, resourceServerAddress){ 
    this.empList = []; 

    // Method for clearing search employee list 
    this.clearEmpList = function(){ 
     this.empList = []; 
    } 

    // Method for fetching employee search list 
    this.fetchEmpList = function(){ 
     return this.empList; 
    } 

    // Method for making employee search 
    this.searchEmpList = function(empName){ 
     var postData = { 
        empName:empName, 
       }; 

     $http({ 
      method: 'POST', 
      url: resourceServerAddress, 
      data : postData 
     }).then(function successCallback(response) { 
      console.log('Response Data : '+response); 

      if(response['data']['status'] === 'success'){ 
       console.log('Response received successfully with status=success'); 

       if(response['data']['data'].length) 
       { 
        console.log('matches found for employee search'); 
        this.empList = response; 
       } 
       else 
       { 
        console.log('no matches found for employee search'); 
        this.empList = []; 
       } 
      } 

      if(response['data']['status'] === 'error'){ 
       console.log('Response received successfully with status=error'); 
      } 

     }, function errorCallback(response) { 
      console.log('Error occur at time of processing request'); 
     }); 
    } 
}); 

次に、このサービスモジュールからデータを取得するために、私のコントローラで次のコードを使用しています。

employeeSearchService.searchEmpList(empName); 
empSearchResponseList = employeeSearchService.fetchEmpList(); 
console.log('Search response from server module : '+empSearchResponseList); 

私は、私はサービスモジュールからすべてのコンソールメッセージで私のAJAX呼び出しからデータを取得しています私のクロムコンソールから見ることができます。しかし、コントローラ変数でそれらのデータをキャッチすることはできません。

私は 'searchEmpList()' & 'fetchEmpList()'を使用していますが、これは正しい方法ではありません。しかし、それを修正する方法を見つけることができません。

コントローラコードが更新---いくつかのガイダンスに-.-

が必要----

// Controller for application Home route 
app.controller("HomeController", function($scope, $state, $location, $ionicHistory, $ionicSideMenuDelegate, $http, resourceServerAddress, employeeSearchService) { 

    console.log('At home controller'); 

    // Check application session. If it's found not exist redirect user to login page 
    if(window.localStorage.getItem("access_token") === "undefined" || window.localStorage.getItem("access_token") === null) { 
     $ionicHistory.nextViewOptions({ 
      disableAnimate: true, 
      disableBack: true 
     }); 

     console.log('Redirecting user to login page-222'); 
     $state.go("login"); 
    } 

    $scope.empName    = ''; 
    $scope.alertMsgBox   = false; 
    $scope.alertMsgText   = ''; 
    $scope.employees    = []; 
    $scope.resourceServerAddress = resourceServerAddress; 

    var empSearchResponseList=null; 

    // Method for employee search 
    $scope.searchEmployee = function(form){ 
     console.log('Employee name entered : '+$scope.empName); 
     console.log('Employee name character length : '+$scope.empName.length); 

     if($scope.empName.length >= 3){ 

      var postData = { 
        Emp_Name:$scope.empName, 
        access_token:window.localStorage.getItem('access_token'), 
        session_id:window.localStorage.getItem('session_id') 
       }; 

      $http({ 
       method: 'POST', 
       url: resourceServerAddress, 
       data : postData 
      }).then(function successCallback(response) { 
       console.log('Response Data : '+response); 

       if(response['data']['status'] === 'success'){ 
        console.log('Response received successfully with status=success'); 

        if(response['data']['data'].length) 
        { 
         console.log('matches found for employee search'); 
         $scope.employees = response['data']['data']; 
         $scope.alertMsgBox = false; 
        } 
        else 
        { 
         console.log('no matches found for employee search'); 
         $scope.alertMsgBox = true; 
         $scope.employees = []; 
         $scope.alertMsgText = 'No matches found.'; 
        } 
       } 

       if(response['data']['status'] === 'error'){ 
        console.log('Response received successfully with status=error'); 
       } 

      }, function errorCallback(response) { 
       console.log('Error occur at time of processing request'); 
      }); 
     } 
    } 


    // Method for showing employee profile 
    $scope.showEmpProfile = function(empId){ 
     console.log('HomeCtrl - click on profile image of emp id : '+empId); 

     // Redirecting to home page 
     $state.go('app.emp-profile', {empId:empId}); 
    } 
}); 

答えて

1

は、あなたのサービスが動作することを確認していますか? 私はこの構文を好む:

.service('Service', function() { 
    var Service = { 
     //methods here 
    } 
    return Service; 
    }); 

をそして、あなたは「この」がハードワークを必要としません。

+0

のための素晴らしいスタイルガイドFOT

ねえ、迅速な回答に感謝します。うん、私のサービスが働いている。私のコントローラAJAXからsearchEmpList()を呼び出しているときはいつでもコールが行われています。私はちょうどこれを参照しています - http://viralpatel.net/blogs/angularjs-service-factory-tutorial/ – mi6crazyheart

+0

私は問題があなたのajax要求にあるかもしれないと思う。それを包装する$ qサービスを試してみてください –

+0

'$ http'を' $ q'で囲む必要はありません。ドキュメントごと* $ http APIは、$ qサービスによって公開される遅延/約束APIに基づいています。 – koox00

4

も混乱しているようです。 $http呼び出しが非同期に行われるため、fetchを呼び出すと、空の配列がフェッチされます。 私はまた、あなたがコントローラで.then()を使用するために$httpを返すために持っていることに気づく。この

this.searchEmpList = function(empName){ 
    var postData = { 
       empName:empName, 
      }; 

    return $http({ 
     method: 'POST', 
     url: resourceServerAddress, 
     data : postData 
    }).then(function(response) { 
     console.log('Response Data : '+response); 

     if(response['data']['status'] === 'success'){ 
      console.log('Response received successfully with status=success'); 

      if(response['data']['data'].length) 
      { 
       console.log('matches found for employee search'); 
       return response['data']['data']; 
      } 
      else 
      { 
       console.log('no matches found for employee search'); 
       return []; 
      } 
     } 

     if(response['data']['status'] === 'error'){ 
      console.log('Response received successfully with status=error'); 
     } 

    }, function(response) { 
     console.log('Error occur at time of processing request'); 
    }); 
} 

のようにして、コントローラ

employeeSearchService.searchEmpList(empName).then(function(data){ 
    console.log('data is ready', data); 
}); 

で何かをするだろう(約束を返します)。角度check

+0

返信いただきありがとうございます。あなたのコードは正常に動作しています。しかし、AJAXレスポンスをService内の変数に格納して、別のメソッドでそのレスポンスデータを取得することはできません。 私はこれを望んでいます。ユーザーがアプリからログアウトするときに、この検索リスト変数を空にする必要があります。他の従業員の検索と検索リストの取得を行っている場合は、今現在何が起こっているのですか?その後、ログアウトしてもう一度ログインすると、検索データがページに表示されます。 – mi6crazyheart

+0

コントローラは見えますか?どのように 'searchEmplist'を呼びますか?ユーザーアクションで?あなたがその州に入るたびに呼び出されますか? – koox00

+0

ちょっと私のコントローラコードで投稿を更新しました。今、全部の「検索」のものはコントローラの内部だけに行きます。しかし、私はその機能をサービスに取り除いてそのコードをリファクタリングしています。だから、私は既に共有しているそのユーザーのLOGOUT問題を処理することができます。 – mi6crazyheart

関連する問題