2015-11-19 40 views
5

Tôi hơi mới trong góc. Tôi đã xây dựng mô-đun Dịch vụ 'Tìm kiếm nhân viên'. Đây là mã ...Cách gọi phương thức dịch vụ góc từ bộ điều khiển?

// 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'); 
     }); 
    } 
}); 

Sau đó, tôi đang sử dụng mã sau đây trong Bộ điều khiển để tìm nạp dữ liệu từ mô-đun Dịch vụ này.

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

Tôi có thể thấy từ bảng điều khiển chrome của mình, tôi nhận dữ liệu từ cuộc gọi AJAX với tất cả thông báo bảng điều khiển từ Mô-đun dịch vụ. Nhưng, không thể bắt những dữ liệu đó trong biến Controller.

Tôi nghĩ cách này, tôi đang sử dụng 'searchEmpList()' & 'fetchEmpList()' trong bộ điều khiển của tôi, nó không đúng cách. Nhưng, không thể tìm ra cách sửa đổi cái đó.

Cần Một số hướng dẫn -.-

--- khiển Mã cập nhật ----

// 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}); 
    } 
}); 

Trả lời

1

Bạn có chắc chắn rằng bạn công trình dịch vụ? tôi thích cú pháp sau:

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

Và bạn không cần phải làm việc chăm chỉ với ' này'.

+0

Hey, nhờ trả lời nhanh chóng. Vâng, Dịch vụ của tôi hoạt động. Bất cứ khi nào tôi gọi 'searchEmpList()' từ cuộc gọi điều khiển AJAX của tôi đang diễn ra. Tôi chỉ đề cập đến điều này - http://viralpatel.net/blogs/angularjs-service-factory-tutorial/ – mi6crazyheart

+0

Tôi nghĩ rằng vấn đề có thể là trong bạn yêu cầu ajax. Hãy thử sử dụng $ q dịch vụ fro gói nó –

+0

không cần phải quấn '$ http' với' $ q'. Theo tài liệu * API $ http dựa trên API hoãn lại/hứa hẹn được hiển thị bởi dịch vụ $ q * – koox00

4

this cũng có vẻ khó hiểu đối với tôi. các cuộc gọi $http được thực hiện không đồng bộ để khi bạn gọi fetch, nó sẽ tìm nạp một mảng trống. tôi sẽ làm một cái gì đó như thế này

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'); 
    }); 
} 

và trong bộ điều khiển

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

Cũng cần lưu ý rằng bạn phải trả lại $http để sử dụng .then() trong bộ điều khiển (trả về một lời hứa).

Fot một styleguide tuyệt vời cho góc check

+0

Cảm ơn bạn đã trả lời. Mã của bạn đang hoạt động tốt. Tuy nhiên, chúng tôi không thể lưu trữ phản hồi AJAX đó bên trong một biến trong Dịch vụ và tìm nạp dữ liệu phản hồi đó bằng một phương pháp khác. Tôi muốn điều này, bởi vì ... khi người dùng đăng xuất khỏi ứng dụng, tôi cần xóa biến Danh sách tìm kiếm này. Khác, ngay bây giờ những gì đang xảy ra ... nếu tôi đang làm bất kỳ tìm kiếm nhân viên và nhận được danh sách tìm kiếm. Sau đó, nếu đăng xuất khỏi ứng dụng và đăng nhập lại, dữ liệu Tìm kiếm sẽ hiển thị trên trang. – mi6crazyheart

+0

Tôi có thể xem bộ điều khiển của bạn không? Làm thế nào để bạn gọi 'searchEmplist'. Trên hành động của người dùng? hay nó được gọi mỗi khi bạn vào trạng thái đó? – koox00

+0

Tôi đã cập nhật bài đăng của mình bằng mã Bộ điều khiển. Ngay bây giờ, toàn bộ công cụ 'Tìm kiếm' chỉ nằm trong bộ điều khiển.Nhưng, tôi đang tái cấu trúc mã đó bằng cách xóa chức năng đó ra một Dịch vụ. Vì vậy, tôi có thể xử lý vấn đề người dùng LOGOUT mà tôi đã chia sẻ. – mi6crazyheart

Các vấn đề liên quan